Javascript 将带有ajax请求的数组发送到php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14846496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:07:39  来源:igfitidea点击:

Send array with ajax request to php

javascriptphpjqueryajax

提问by Mahmood Rehman

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:

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

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

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

In the above code stuffis 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_5is the key and 9become the value for that key.

在上面的代码中stuff是一个包含记录的数组。我怎样才能用上面的代码发送这个数组,然后在 PHP 中我想处理这个数组,就像ques_5是键一样,并9成为该键的值。

回答by Sherin Jose

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

您可以将数据作为JSON对象传递给 PHP 脚本。假设你的 JSON 对象是这样的:

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

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

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

1. Pass the object as a string:

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

AJAX call:

AJAX 调用:

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

You can handle the data passed to the result.phpas :

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

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

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

2. Pass the object directly:

2.直接传递对象:

AJAX call:

AJAX 调用:

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

Handle the data directly in result.phpfrom $_POSTarray as :

直接result.php$_POST数组中处理数据:

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

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

这里我推荐第二种方法。但你应该同时尝试:-)

回答by FloatingCoder

If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)

如果你想发送键值对,这就是我所看到的,最好使用 PHP JSON 库(比如这个...... http://php.net/manual/en/book.json.php)

Then you can send actual key value pairs, using JSON format like... {"ques_5" : "19", "ques_4": "19"}

然后你可以发送实际的键值对,使用 JSON 格式,如... {"ques_5" : "19", "ques_4": "19"}

回答by Dipesh Parmar

Try this

尝试这个

var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));

above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.

上面的代码将输出以逗号分隔的字符串,9,ques_5,19,ques_4然后将其粘贴到ajax调用中。

And then in php explodethat string.

然后在php explode那个字符串中。

Other possible solutions.

其他可能的解决方案。

First

第一的

var obj = { 'item1': 'value1', 'item2': 'value2' };

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

Second

第二

var a = $.JSON.encode(obj);

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

In PHP File

<?php
    $json = $_POST["data"]
    var_dump(json_decode($json));
?>

回答by Dinkar Thakur

You can send the array in jsonformat to the php and then use json_decodefunction to get back the array like

您可以将array in json格式发送到 php,然后使用json_decode函数来取回数组,例如

In ajax call you have to send json for that you need to first make array of the values so that you get it in right form so that you json look like {"ques_5":"9","ques_4":19}

在 ajax 调用中,您必须为此发送 json,您需要首先制作值的数组,以便以正确的形式获取它,以便您的 json 看起来像 {"ques_5":"9","ques_4":19}

and use in ajax call

并在 ajax 调用中使用

 data: JSON.stringify(`your created json`),
 contentType: "application/json; charset=utf-8",
 dataType: "json",

IN PHP it look like

在 PHP 中它看起来像

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>

回答by Jean Pierre Porre

I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function

我想分享一个对我有用的完整示例,以避免为每个 PHP 函数创建每个 JavaScript 函数

// on the HTML side a simple JavaScript call from a link

// 在 HTML 端,一个来自链接的简单 JavaScript 调用

 <a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>

// on JavaScript side

// 在 JavaScript 端

function CargaZona(fc, div, params) {
    var destino = "#" + div;
    var request = $.ajax({
        url : "inc/phpfunc.php",
        type : "POST",
        data : {
            fc : fc,
            params : JSON.stringify(params)
        },
        dataType : "html"
    });

    request.done(function (msg) {
        $(destino).html(msg);
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// on phpfunc.php page

// 在 phpfunc.php 页面

<?php

$params = "{'key1':'value1','key2':'value2'}"; 
$fc = 'def';
if (isset($_POST['fc']))   {    $fc = $_POST['fc']; }
if (isset($_POST['params']))   {    $params = $_POST['params']; }

switch ($fc) {
    default:
        call_user_func($fc,$params);
}

function democonllamada($params) {
    $params = json_decode("$params", true);
    echo "ok llegaron".$params['key1'];
}

?>