开发者

Send JavaScript object to web server call via jQuery - what is the correct way?

I'm trying to send JSON data to my web server via jQuery and I'm running into an error. Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}

code I am testing:

var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
    // code remove notification from the DOM
    });
});

Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.

UPDATE

code I got to work

var obj 开发者_如何学Python= {
    id: 45,
    isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url, 
         type:'POST', 
         contentType: 'application/json', 
         data: json, 
         success: function(data, textStatus) {
            // do stuff
         }
});

My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.


You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/

Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.

var obj = {
  'id':45,
  'isRead':true
};
$.ajax({
  url: "/notification/read",
  data: obj,
  success: function(data, textStatus){
    /* code here */
  }
});


$.ajax(url, obj);

You need to send an object as second param

{success: success, data: data}


Documentation is here:

http://api.jquery.com/jQuery.ajax/

You have to pass parameters as one object, not multiple ones

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜