首页 \ 问答 \ 使用Backbone.js的POST方法发送数据(Send data using POST method with Backbone.js)

使用Backbone.js的POST方法发送数据(Send data using POST method with Backbone.js)

我使用Backbone.js实现了一个简单的登录系统。

我试图使用HTTP POST方法将用户名和密码传递给处理用户身份验证的Controller类。

public function sessions() {
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
        $this->login();
    } elseif ($this->input->server('REQUEST_METHOD') == 'GET') {
        $this->index();
    } elseif ($this->input->server('REQUEST_METHOD') == 'DELETE') {
        $this->session->sess_destroy();
        $this->index();
    }
}

Backbone.js代码段:

$(document).ready(function() {

    var Session = Backbone.Model.extend({
        url: function() {
            var link = "http://<?php echo gethostname(); ?>/reddit/index.php/welcome/sessions";
            return link;
        },
        defaults: {
            username: null,
            password: null
        }
    });

    var model = new Session();

    var DisplayView = Backbone.View.extend({
        el: ".complete",
        model: model,
        type: 'POST',
        initialize: function() {
            this.listenTo(this.model, "sync change", this.gotdata);
        },
        events: {
            "click #signin": "getdata"
        },
        getdata: function(event) {
            event.preventDefault();
            var username = $("input#username").val();
            var password = $("input#password").val();
            this.model.set({ username: username, password: password });
            this.model.fetch();
        },
        gotdata: function() {
            console.log(this.model.get('username'));
            console.log(this.model.get('password'));
            $("#base-nav").load(location.href + " #base-nav");
            $("#signin-form").load(location.href + " #signin-form");
        }
    });

    var displayView = new DisplayView();
});

我当前使用了type属性来定义HTTP方法类型POST。 但这似乎不起作用,因为只能使用开发人员控制台观察GET请求。

需要注意的是,当我删除event.preventDefault(); 单击链接时阻止页面重新加载( 防止Backbone pushState上的完整页面重新加载 )POST请求似乎已成功传递到后端,尽管页面重新加载会阻止预期的目标行为。

我们如何使用Backbone.js的POST请求轻松发送数据?


I have implemented a simple login system using Backbone.js.

I am attempting to pass the username and password using HTTP POST method to the Controller class which handles the user authentication.

public function sessions() {
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
        $this->login();
    } elseif ($this->input->server('REQUEST_METHOD') == 'GET') {
        $this->index();
    } elseif ($this->input->server('REQUEST_METHOD') == 'DELETE') {
        $this->session->sess_destroy();
        $this->index();
    }
}

The Backbone.js code segment:

$(document).ready(function() {

    var Session = Backbone.Model.extend({
        url: function() {
            var link = "http://<?php echo gethostname(); ?>/reddit/index.php/welcome/sessions";
            return link;
        },
        defaults: {
            username: null,
            password: null
        }
    });

    var model = new Session();

    var DisplayView = Backbone.View.extend({
        el: ".complete",
        model: model,
        type: 'POST',
        initialize: function() {
            this.listenTo(this.model, "sync change", this.gotdata);
        },
        events: {
            "click #signin": "getdata"
        },
        getdata: function(event) {
            event.preventDefault();
            var username = $("input#username").val();
            var password = $("input#password").val();
            this.model.set({ username: username, password: password });
            this.model.fetch();
        },
        gotdata: function() {
            console.log(this.model.get('username'));
            console.log(this.model.get('password'));
            $("#base-nav").load(location.href + " #base-nav");
            $("#signin-form").load(location.href + " #signin-form");
        }
    });

    var displayView = new DisplayView();
});

I have used the type attribute currently to define the HTTP method type POST. But this does not seem to work as only GET requests can be observed using the developer console.

It has to be noted that when I remove event.preventDefault(); which prevents page reload upon clicking a link (Preventing full page reload on Backbone pushState) the POST request seems to be successfully delivered to the back-end although the page reload prevents the intended target behavior.

How do we easily send data using POST request with Backbone.js?


原文:https://stackoverflow.com/questions/41601819
更新时间:2022-06-15 13:06

最满意答案

这是您帖子中的JavaScript。

如果你这样做:

function myFunction() {
    var x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "You selected: " + x;
    console.log("x:",x);
}

x在函数的范围内,因此可用。

在全局范围内定义类似变量通常是一种不好的做法。

var x = {};
function myFunction() {
    x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "You selected: " + x;
 }
myfunction();// call it
console.log("x:",x);

详细版本:(基本上相同但对象的显式window )注意我添加了如何获取所选值。

window.x = {};

function myFunction() {
  window.console.log("in here");
  var selectElem = document.getElementById("mySelect");
  var optsCount = selectElem.options.length;
  var index = selectElem.selectedIndex;
  window.console.log("opts", optsCount, index);
  // return the value of the selected option
  window.console.log(selectElem.options[selectElem.selectedIndex].value)
  window.x = selectElem.options[selectElem.selectedIndex].value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
window.myFunction(); // call it
window.console.log("x:", window.x);

这是最后一个例子的小提琴: https//jsfiddle.net/MarkSchultheiss/bqwd784p/

这里没有jQuery只是JavaScript。


This is the JavaScript from your post.

If you do this:

function myFunction() {
    var x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "You selected: " + x;
    console.log("x:",x);
}

x is in the scope of the function and thus is available.

It is generally a bad practice to define variables like that in the global scope.

var x = {};
function myFunction() {
    x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "You selected: " + x;
 }
myfunction();// call it
console.log("x:",x);

Verbose version of this: (basically the same but explicit window on the objects) Note I added how to get the selected value.

window.x = {};

function myFunction() {
  window.console.log("in here");
  var selectElem = document.getElementById("mySelect");
  var optsCount = selectElem.options.length;
  var index = selectElem.selectedIndex;
  window.console.log("opts", optsCount, index);
  // return the value of the selected option
  window.console.log(selectElem.options[selectElem.selectedIndex].value)
  window.x = selectElem.options[selectElem.selectedIndex].value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
window.myFunction(); // call it
window.console.log("x:", window.x);

Here is a fiddle of the last example:https://jsfiddle.net/MarkSchultheiss/bqwd784p/

No jQuery here just JavaScript.

相关问答

更多
  • 首先 - 你错过了function和CheckDegree之间的CheckDegree - 所以Javascript实际上不会识别该函数。 如果要在提交时调用该函数,则需要在其中放置一个操作。 目前你的功能只是分配一个变量,实际的比较和alert部分在函数之外: function CheckDegree(){ // Declare the var cd with ...
  • 从代码中删除它: $("#countrySelect option:selected").attr("name"); 但您应该使用data-*属性在HTML元素中存储随机数据。 jQuery使它们易于使用: http : //api.jquery.com/data/ Remove the this from your code: $("#countrySelect option:selected").attr("name"); But you should really be using data- ...
  • 你可以动态地添加你的选项。 例如 // This assumes that this is the only select element on the page. // Also, this would have to run in a script block // after the select element is added to the page. var select = document.querySelector('select'); select.options.add(new Op ...
  • ...
  • 您已经在选择器中选择了选项 - 无需查找选项 - 因为这将返回一个空数组 $('.selectboxes option:selected').hide(); // get rid of .find('option') 要免除this值..我猜你在指的是所选的值..你可以使用:not as undefined陈述 $(".selectbox option:not(:selected)").show(); 您可以取出内联onChange,因为您正在使用jQuery ..并将更改事件处理程序绑定到dom上的s ...
  • 这是您帖子中的JavaScript。 如果你这样做: function myFunction() { var x = document.getElementById("mySelect").value; document.getElementById("demo").innerHTML = "You selected: " + x; console.log("x:",x); } x在函数的范围内,因此可用。 在全局范围内定义类似变量通常是一种不好的做法。 var x = {}; f ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)