发布带有ajax问题的json

时间:2016-03-16 13:49:22

标签: jquery json ajax cherrypy

我有以下代码,它总是生成404错误(未找到):

data = Object {a: "500000", b: "4"}
postJson(data);


function postJson(data){
    $.ajax({
                url: '/url/postJson',
                type: 'POST',
                data: data, //also tried "JSON.stringify(data)"
                dataType: "json",
                contentType: "application/json",
                success: function (data, textStatus, jqXHR) {

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('error')
                }
            });
}

在服务器端:

@cherrypy.expose
def postJson(self, data):
    print data //just for the test

可能是什么问题?

3 个答案:

答案 0 :(得分:0)

404是来自服务器端的状态。 要检查是否存在并访问您的网址,请尝试卷曲:

curl -X POST -H "Content-Type: application/json" --data '{a: "500000", b: "4"}' http://url/portJson

我经常使用POST Django后端的100%工作函数(我没有设置'contentType'和'dataType',但我设置了'X-CSRFToken'):

function sendAjaxRequest(url, data, done, always, fail, reqType, timeout) {
    var _done = function() {};
    var _always = function() {};
    var _fail = function(jqXHR,status,err){
        alert('Error (' + status + '): ' + err + '\n' + jqXHR.responseText);
    }
    var _reqType ='POST'
    var _timeout = 60000;

    if (typeof done !== 'undefined') _done = done;
    if (typeof always !== 'undefined') _always = always;
    if (typeof fail !== 'undefined') _fail = fail;
    if (typeof reqType !== 'undefined') _reqType = reqType;
    if (typeof timeout !== 'undefined') _timeout = timeout;

    var csrftoken = $.cookie('csrftoken');

    $.ajax({
        url: url,
        headers:{ 'X-CSRFToken': csrftoken },
        data: data,
        cache: false,
        type: _reqType,
        timeout: _timeout
    }).done(_done).always(_always).fail(_fail);
};

使用:

var data = {'a': "5000", 'b': "4"};

sendAjaxRequest(
    "/my/url/",
    data,
    function(response, textStatus, jqXHR) {// done
       // do work
    }, undefined, undefined, 'POST'
);

答案 1 :(得分:0)

通过this answer中的代码,看起来您的JSON格式需要更新。试试这个。

data = {data: {a: "500000", b: "4"}}

答案 2 :(得分:0)

在服务器上更改:

@cherrypy.expose
def postJson(self, data):
    print data //just for the test

为:

@cherrypy.expose
@cherrypy.tools.json_in
def postJson(self):
    data = cherrypy.request.json
    print data //just for the test