繁体   English   中英

如何使用ajax,json和php遍历jquery中的多行?

[英]How to iterate through multiple rows in jquery using ajax, json, and php?

我有一个PHP页面,它返回像这样的json:

while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
        $rows[] = $row;
}
print json_encode($rows);

当我运行php页面时,我返回类似以下内容:

[{"phone":"1234567"},{"phone":"1234567"}]

这是我的jQuery代码:

   $.ajax({
        url: 'test.php',
        type: 'POST',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function(response) {

             $.each(response, function() { 
                $.each(this, function(key, value){
                    alert(key + " --> " + value); 
                });
            });

        }
   });

});

我是从另一个SO问题得到的。 这将为我提供警报中的键和值。 这只是为了确保一切正常。 我进行了搜索,但无法弄清楚如何获得一个值。 说我想要这个名字,我要输入什么? 我努力了:

success: function(response) {
 var obj = $.parseJSON(response);
 alert( obj.phone );
}

但是由于它是多行,除非我有行,否则它将不起作用,并且当我有这样的一行时,它也会失败:

echo json_encode(array("phone" => "123")

如何从行中获取单个值? 如何遍历多行并且仅获取列值之一?

response变量是一个对象数组。 要访问response变量中的单个索引:

var phone = response[0].phone;//replace `0` with the index you want

如果您最终在循环中遍历整个响应,请确保按以下方式进行操作以获得最佳性能:

var len = response.length;
for (var i = 0; i < len; i++) {
    console.log(response[i].phone);
}

检出此jsperf,以查看这种类型的循环比for(i in array)快得多: http : //jsperf.com/for-in-tests

响应JSON是一个数组。 要获取第一个电话号码,请通过response[0]检索第一个对象,然后使用.phone获取属性:

    success: function(response) {  //response = array, when using dataType:"JSON"
         alert(response[0].phone);
    }

将0替换为0到response.length之间的任何数字,以获取相应的电话属性。

使用Javascript:

for (var i; i < response.length; i++) {
    console.log(response[i].phone);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM