如何使用jQuery的AJAX和PHP数组复出之作 [英] How to work with jQuery AJAX and PHP array return

查看:123
本文介绍了如何使用jQuery的AJAX和PHP数组复出之作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个jquery ajax请求;

I have a jquery ajax request like;

$.ajax({
    type: 'POST',
    url: 'processor.php',
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',
    cache: false,
    success: function(result) {
      if(result){
        alert(result);
      }else{
        alert("error");
      }
    }
});

的处理程序 processor.php 设置为返回数组等等;

The handler processor.php is set to return an array like;

$array = array("a","b","c","d");
echo $array;

我想这样做在此基础上的客户端操作。如果说阵列[0]为'B',我想提醒喜。同样地,如果数组[2]是'X',我想提醒你好,等等。我如何过滤数组中的元素,以抓住他们的数据?

I want to do action in client side based on this. Say if array[0] is 'b', I want to alert "hi". Again if array[2] is 'x', I want to alert "hello", and so on. How can I filter array elements in order to grab their data?

推荐答案

您将不得不返回数组EN codeD在JSON形式类似以下

You will have to return the array encoded in the json form like following

$array = array("a","b","c","d");
echo json_encode($array);

那么你就可以访问它的JavaScript将其转换回数组/对象像

then you can access it in javascript converting it back to an array/object like

var result = eval(retuned_value);

您也可以通过所有的数组元素使用导航for循环

You can also navigate through all array elements using a for loop

for (var index in result){
    // you can show both index and value to know how the array is indexed in javascript (but it should be the same way it was in the php script)
    alert("index:" + index + "\n value" + result[index]);
}


在你的code就应该是这个样子:


in your code it should look something like:

$array = array("a","b","c","d");
echo json_encode( $array );

jQuery脚本

$.ajax({
    type: 'POST',
    url: 'processor.php',
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',
    cache: false,
    success: function(result) {
      if(result){
        resultObj = eval (result);
        alert( resultObj );
      }else{
        alert("error");
      }
    }
});

这篇关于如何使用jQuery的AJAX和PHP数组复出之作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆