将带有ajax请求的数组发送到php [英] Send array with ajax request to php

查看:91
本文介绍了将带有ajax请求的数组发送到php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这样的数组 [9,ques_5,19,ques_4] 。现在我想将它从JS发送到PHP,但我没有得到正确的结果。我的JS代码是:

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:

$(".button").click(function(e) {

    e.preventDefault();
    $.ajax({
        type    : 'post', 
        cache   : false,
        url     : 'test/result.php',
        data    : {result : stuff},
        success: function(resp) {
            alert(resp);
        }
    });
});

在上面的代码中东西是一个数组其中包含记录。如何使用上面的代码发送此数组,然后在PHP中我想处理此数组,如 ques_5 是键和 9 成为该键的值。

In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.

推荐答案

您可以将数据作为 JSON 对象。假设您的JSON对象如下:

You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:

var stuff ={'key1':'value1','key2':'value2'};

您可以通过两种方式将此对象传递给php代码:

You can pass this object to the php code in two ways:

1。将对象作为字符串传递:

AJAX调用:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : {result:JSON.stringify(stuff)},
    success : function(response) {
        alert(response);
    }    
});

您可以处理传递给 result.php的数据 as:

You can handle the data passed to the result.php as :

$data    = $_POST["result"];
$data    = json_decode("$data", true);

//just echo an item in the array
echo "key1 : ".$data["key1"];

2。直接传递对象:

AJAX通话:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : stuff,
    success : function(response) {
        alert(response);
    }    
});

直接处理数据 result.php $ _ POST 数组为:

Handle the data directly in result.php from $_POST array as :

//just echo an item in the array
echo "key1 : ".$_POST["key1"];

这里我建议第二种方法。但你应该尝试两种方法: - )

Here I suggest the second method. But you should try both :-)

这篇关于将带有ajax请求的数组发送到php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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