2016-01-17 533 views
3

我想将数组传递给我的Ajax请求,以便我可以使用相同的查询更新多个元素。这是我做的:使用PHP将数组传递给Ajax

我的Ajax调用:

$("body").on("focusout", "input", function() { 
    var id = ($(this).attr("id")); 
    var container = '#' + id + "_ck"; 
    var data_type = ($(this).attr("data-type")); 
    var text = document.getElementById(id).value; 
    $.ajax({ 
     url: 'ajax-php.php', 
     type: 'post', 
     data: { 'action': 'input_ck', 'id': id, 'text': text, 'data_type': data_type }, 
     success: function (data, status) { 
      $(container).html(data); <-------------------------------- PHP RESPONSE 
     }, 
     error: function (xhr, desc, err) { 
      console.log(xhr); 
      console.log("Details: " + desc + "\nError:" + err); 
     } 
    }); 
}); 

现在我知道我可以返回一个数组,这样的数据包含我的JSON数组。

比方说,PHP返回此:

$arr($var1,$var2); 
echo json_encode($arr); 

我可以做这样的事情早在我的jQuery Ajax的脚本?

foreach(data as value){ 
    i=0; 
    $(container[i]).html(data[i]); 
    i++; 
} 

我也将成为一个阵列出来的各种器皿。 我不确定这里的语法,但它可能吗?

+0

你想传递一个数组或返回一个数组,你可以循环与jquery? –

+0

是的多数民众赞成在我想要做 – MadeInDreams

回答

2

是当然可以,但你需要调整与AJAX性能满足响应的期望输出类似以下内容:

$.ajax({ 
    url: 'ajax-php.php', 
    type: 'post', 
    dataType : 'json', //<----- add here 
    data: { 'action': 'input_ck', 'id': id, 'text': text, 'data_type': data_type }, 
    success: function (data, status) { 
     // $(container).html(data); <-------------------------------- PHP RESPONSE 
     // Add here 
     //i=0; 
     // you can either use $.each or forEach or native for loops here 
     $.each(data, function(i,e){ //< i = index, e = element 
     // i'm not sure with this selector 
     // you need to show what kind of container element did you have   
     $(container[i]).html(data[i]);// or easier if using e.property_name 
     //i++; 
     } 
    }, 
    error: function (xhr, desc, err) { 
     console.log(xhr); 
     console.log("Details: " + desc + "\nError:" + err); 
    } 
}); 
+0

更快,然后我tought谢谢 – MadeInDreams

+0

不客气的队友! –

1

PHP

$json = array('vals' => array($var1, $var2)); 
header('Content-Type: application/json'); 
echo json_encode($json) 

jQuery的

if(data.vals){ 
    $.each(data.vals, function(key, value) { 
     $(container[key]).html(value); 
    }); 
} 

未经测试