2013-12-19 91 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"

相關問題