开发者

Jquery JSON response handling

I have an aj开发者_如何学Goax query written in jQuery that is returning valid JSON in this format

$.ajax({
   type     : 'POST',
   url      : 'ajax/job/getActiveJobs.php',
   success  : function(data){
       if(data[''] === true){
           alert('json decoded');
       }

       $('#waiting').hide(500);
       $('#tableData').html(data['content']);
       $('#message').removeClass().addClass((data.error === true)
       ?'error':'success').text(data.msg);
       if(data.error === true)
           $('#message')

   },
   error    : function(XMLHttpRequest, textStatus, errorThrown){
       $('#waiting').hide(500);
       $('#message').removeClass().addClass('error').html(data.msg);
   } })

I take it this is not correct as it is not displaying the data, if I use

$('#mydiv').html(data);

I get all of the data back and displayed.

any help is really appreciated


Set the dataType to be json so jQuery will convert the JSON to a JavaScript Object.

Alternatively, use getJSON() or send the application/json mime type.


Either set dataType to json or use var json = JSON.parse(data) to do it manually.

EDIT:

I'm adding this because somebody else suggested eval, don't do this because it gets passed straight into a JSON object without any sanitation first, allowing scripts to get passed leading straight into an XSS vulnerability.


The data is the Json so you will want to do this:

success: function (data) {
  var newobject = eval(data);
  alert(newobject.msg);

}

or do this:

$ajax({
    url: url,
    data: {},
   dataType: "json",
   success: function (newObject) {
   alert(newobject.msg);
}
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜