我正在使用bootstrap 3和jquery开发我的应用程序。我的问题是,如果不使用JSON.stringify而不是formValues,为什么我得到null对象?
在使用JSON.stringify之前
var that = this;
var formValues = {
userId: 315,
locale: "en",
};
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formValues,
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
使用JSON.stringify
之后var that = this;
function formToJSON() {
return JSON.stringify({
"userId": 315,
"locale": "en",
});
}
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formToJSON(),
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
提前多多感谢。
答案 0 :(得分:1)
如果data
属性是一个对象,jQuery会将其序列化为$.param
:
> $.param({userId: 315, locale: "en"});
"userId=315&locale=en"
如果你传入一个字符串,jQuery不会序列化它。使用Web浏览器的开发人员工具查看请求。
答案 1 :(得分:0)
因为那不是一个合适的数据字符串。
var formValues = "userid=5&locale=en";
答案 2 :(得分:0)
因为JS对象不是JSON。 JSON是字符串,JS对象是一个对象。如果fetch
使用jQuery.ajax
,则它需要JS对象或查询字符串(不 JSON):"userId=315&locale=en"
。