3

我可以在backbone.js中设置content-type和吗?POST

this.save(data, {
    success: function (user) {
        callback(user.get('LoginStatus'))
    },

    error: function (user, result, xhr) {

    }
});

当我尝试进行 REST 服务调用时,我收到了错误的请求,它在提琴手中工作。我们需要设置类型和内容类型吗?

这是我得到的错误

[ERROR][TiHttpClient(  636)] (TiHttpClient-1) [13340,13340] HTTP Error (org.apache.http.client.HttpResponseException): Bad Request
[ERROR][TiHttpClient(  636)] org.apache.http.client.HttpResponseException: Bad Request
[ERROR][TiHttpClient(  636)]    at ti.modules.titanium.network.TiHTTPClient$LocalResponseHandler.handleResponse(TiHTTPClient.java:240)
[ERROR][TiHttpClient(  636)]    at ti.modules.titanium.network.TiHTTPClient$LocalResponseHandler.handleResponse(TiHTTPClient.java:199)
[ERROR][TiHttpClient(  636)]    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
[ERROR][TiHttpClient(  636)]    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:637)
[ERROR][TiHttpClient(  636)]    at ti.modules.titanium.network.TiHTTPClient$ClientRunnable.run(TiHTTPClient.java:1217)
[ERROR][TiHttpClient(  636)]    at java.lang.Thread.run(Thread.java:1020)
[ERROR][TiAPI   (  636)]  [REST API] ERROR: " *** FaultException : Object reference not set to an instance of an object."
[ERROR][TiAPI   (  636)]  [REST API] apiCall ERROR: " *** FaultException : Object reference not set to an instance of an object."
4

2 回答 2

8

由于主干fetchsave方法包装了函数,您可以通过将对象直接传递给or函数来jQuery.ajax()在 Backbone 中设置 Content-Type 和 Request MethodjQuery.ajax() settingsfetchsave

例如使用fetch函数:

myModel.fetch({
    type: "POST",
    contentType: "application/json"
});

使用save功能相同:

myModel.save({
    type: "POST",
    contentType: "application/json"
});

另外我注意到你在你的save函数中提供了一个数据属性。如果要将 JSON 作为 POST 数据传递给 URL,则需要在save函数中使用以下语法:

myModel.save({
    data: JSON.stringify(myObject),
    type: "POST",
    contentType: "application/json"
});
于 2013-04-16T13:24:16.590 回答
1

I do not quite understand the error posted but if all you want to do is set the content-type or alter some other default settings in the call, then its quite possible.

If you take a look at the save function for the Model prototype in Backbone, it actually is using this.sync or the default 'Backbone.sync' method to make the call. Checking the Backbone.sync function, you can see that it is actually using the jquery's 'ajax' method to make the call. Note line return $.ajax(_.extend(params, options)); hence you should be able to pass anything as options to it that the jquery's ajax method would take. In the same sync method you can also see you how it is setting the standard default content type, params.contentType = 'application/json';

You could also write your own sync method for the Model and make your own ajax call changing the default parameters. If your Model has its own sync method, it would then be called instead of the default Backbone.sync method.

于 2013-02-07T03:17:26.593 回答