5

我试图在我的 jquery ajax successe 中获得一个 json:工作但我不......

这就是我试图做的:

$("#addcatform").submit(function() {
  var str = $(this).serialize();
  $.ajax({
    type: "POST",
    url: "ajax.php",
    data: str,
    success: function(data){
      var json_x = data;
      alert(json_x.firstName2);
      $('#result').html(json_x.firstName2); 
      $('#result2').html(json_x.b); 
    }
  }); 

  return false;
  event.preventDefault();
}); // submit end

php回应了这一点:

$arr = array ('firstName2'=>'hallo','b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

这有什么问题?谢谢帮忙!!!!

4

3 回答 3

8

你需要在使用它之前解析你的json,

您可以在请求中添加数据类型 - jQuery 将解析您的响应 json

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: 'json',

或者,您可以自己解析它 -

success: function(data){
    var json_x = $.parseJSON(data);
于 2013-07-05T20:28:02.667 回答
2

你可以试试这个:

var data=$.ajax({
        type: "POST",
        url: 'ajax.php',
        data: {
            data:str
        }, 
        async: false,
        dataType: 'json'
    });
    var msg= data.responseText;
    msg=jQuery.parseJSON(msg);

我通常从我的 php 页面发送一个数组或消息“错误”

if(msg=='error')
{
/* do something */
}
else
// use the data

这适用于 jquery 1.6->1.8

编辑:由于 jquery 1.8 async 已被弃用。我会推荐这种格式:

$.ajax({
        type: "POST",
        url: 'ajax.php',
        data: {
            data:str
        }, 
        dataType: 'json',
     ).done(function(data) {
      // do something with the data
     })
   .fail(function() {
    // give appropriate message
    })

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

于 2013-07-05T20:53:14.983 回答
0

data在您的示例中是一个字符串。使用jQuery.getJSON() 编辑:由于您不能使用 getJSON (dûh) 进行 POST 请求,因此请改用.ajax适当的 dataType。这将通过 ajax 检索数据,并将结果字符串解析为 JSON。即使使用getJSON,结果也将是一个数组(或类似对象的数组,不确定)。这没有您可以使用点符号访问的方法或变量。您需要通过data['a'].

$.ajax({
  dataType: "json",
  type: "POST",
  url: "ajax.php",
  data: str,
  success: function(data){
    var json_x = data;
    alert(json_x['firstName2']);
    $('#result').html(json_x['firstName2']);
    $('#result2').html(json_x['b']); 
  } 
}); 
于 2013-07-05T20:28:45.750 回答