2013-12-19 92 views
0

我使用bootstrap 3和jquery来开发我的应用程序。我的问题是,为什么我得到空对象,如果不使用JSON.stringify,而不是formValues?JSON - 为什么我不使用JSON.stringify时得到空对象?

透过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 =那此之后之前;

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); 
    } 
}); 

非常感谢。

回答

1

如果data属性是一个对象,用jQuery的序列化$.param它:

> $.param({userId: 315, locale: "en"}); 
"userId=315&locale=en" 

如果你在一个字符串票代替,jQuery的不序列它。使用您的Web浏览器的开发人员工具查看请求。

0

因为这不是一个合适的数据字符串。

var formValues = "userid=5&locale=en"; 
0

因为JS对象不是JSON。 JSON是字符串,JS对象是一个对象。如果fetch使用jQuery.ajax,它需要JS对象或查询字符串(它是而不是 JSON):"userId=315&locale=en"

相关问题