【问题标题】:Passing arrays to Ajax using PHP使用 PHP 将数组传递给 Ajax
【发布时间】:2016-04-22 10:30:21
【问题描述】:

我想将一个数组传递给我的 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++;
}

我也会用容器制作一个数组。 我不确定这里的语法,但有可能吗?

【问题讨论】:

  • 您是要传递一个数组还是返回一个可以用 jquery 循环的数组?
  • 是的,这就是我想做的事

标签: php jquery arrays ajax


【解决方案1】:

当然可以,但是您需要调整 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);
    }
});

【讨论】:

  • 比我还快谢谢
【解决方案2】:

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);
  });
}

未经测试

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2015-08-21
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多