簡體   English   中英

將帶有ajax請求的數組發送到php

[英]Send array with ajax request to php

我創建了這樣的數組["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);
        }
    });
});

在上面的代碼中, stuff是一個包含記錄的數組。 如何使用上面的代碼發送此數組,然后在PHP中我想處理此數組,如ques_5是鍵, 9成為該鍵的值。

您可以將數據作為JSON對象傳遞給PHP腳本。 假設您的JSON對象如下:

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

您可以通過兩種方式將此對象傳遞給php代碼:

1.將對象作為字符串傳遞:

AJAX電話:

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

您可以將傳遞給result.php的數據處理為:

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

$_POST數組直接處理result.php的數據:

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

在這里我建議第二種方法。 但你應該嘗試兩個:-)

如果你想發送鍵值對,這就是我所看到的,最好使用一個PHP JSON庫(就像這個... http://php.net/manual/en/book.json.php

然后你可以發送實際的鍵值對,使用JSON格式,如... {“ques_5”:“19”,“ques_4”:“19”}

嘗試這個

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

上面的代碼將輸出字符串,用逗號分隔,如9,ques_5,19,ques_4然后將其粘貼到ajax調用。

然后在php explode那個字符串。

其他可能的方法。

第一

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

第二

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

你可以將array in json格式的array in json發送到php,然后使用json_decode函數來獲取數組

在ajax調用中你必須發送json,你需要首先創建值的數組,以便你以正確的形式得到它,這樣你的json看起來像{"ques_5":"9","ques_4":19}

並在ajax調用中使用

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

在PHP中它看起來像

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

我想分享一個適合我的完整示例,以避免為每個PHP函數創建每個JavaScript函數

//在HTML端,來自鏈接的簡單JavaScript調用

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

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

//在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'];
}

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM