为返回的json获取undefined

时间:2011-02-20 16:10:21

标签: php jquery ajax

$.ajax({


            type: "POST",
            url: "ajax.php",
            dataType: 'json',
            data:   "callback=bumpup_contact_us_entry&id=" + id,
            success: function(data){
             $.each(data, function(interval, message) {
                alert(message['request']);
 });            

php:

$the_return = array('request'=>'success','order_id'=>$order_id-1);

echo json_encode($the_return);

我永远无法让json为我工作。我究竟做错了什么?问题与此相关,因为返回html工作正常。

3 个答案:

答案 0 :(得分:2)

$the_return = array('request'=>'success','order_id'=>20);
echo json_encode($the_return);
//output: {"request":"success","order_id":20}

$.each(data,function(i, item) {
   alert( 'request: ' + data.request + ' id: ' +  data.order_id);
});

################################## BEAVIOURS ####################################

$the_return  = array( 'success' , 20 ); 
echo json_encode($the_return);
// output:  ["success",20] 

$.each(data,function(i, item) {
    alert('success: ' + item[0] + 'id: ' + item[1]);
});

$the_return['request'] = array( 'success' , 20 ); 
echo json_encode($the_return);
// output {"request":["success",20]}

$.each(data.request,function(i, item) {
    alert('success: ' + data.request[0] + 'id: ' + data.request[1]);
});

$the_return['message'] = array('request'=>'success','order_id'=>20);
echo json_encode($the_return);
//output: {"message":{"request":"success","order_id":20}}

$.each(data.message,function(i, item) {
    alert( 'request: ' + data.message.request + ' id: ' + data.message.order_id);
});

答案 1 :(得分:1)

试试这样:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    dataType: 'json',
    data: { callback: 'bumpup_contact_us_entry', id: id },
    success: function(data) {
        $.each(data, function(index, message) {
            alert(message.request);
        }
    }
});

或:

$.post('ajax.php', { callback: 'bumpup_contact_us_entry', id: id }, function(data) {
    $.each(data, function(index, message) {
        alert(message.request);
    }
}, 'json');

答案 2 :(得分:0)

在匿名函数中尝试message.request