简体   繁体   English

AJAX jQuery JSON发送数组到PHP

[英]AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. 我试图通过AJAX $ .post发送关联数组到php。 Here's my code: 这是我的代码:

var request = {
        action: "add",
        requestor: req_id,
        ...
    }

    var reqDetails = $("#request_details").val();

    switch(reqDetails){
        case 1: 
            request[note] = $("#note").val();
            break;

        ...

    }

    if(oldRequest()){
        request[previousID] = $("old_id").val();
    }

    $('#req_button').toggleClass('active');
    $.post("scripts/add_request.php", {
        request_arr: JSON.stringify(request)
        }, function(data){
            console.log(data);
            $('#req_button').toggleClass('active');
    }, 'json');

And i'm simply trying to read the received data in my php script: 而且我只是想在我的php脚本中读取接收到的数据:

echo json_decode($_POST["request_arr"]);

But it's not working. 但这不起作用。 I'm a newbie to js, I can't figure out what I'm doing wrong. 我是JS的新手,我不知道自己在做什么错。

Check below link for your reference 检查以下链接以供参考

Sending an array to php from JavaScript/jQuery 从JavaScript / jQuery向php发送数组

Step 1 第1步

$.ajax({
    type: "POST",
    url: "parse_array.php",
    data:{ array : JSON.stringify(array) },
    dataType: "json",
    success: function(data) {
        alert(data.reply);
    }
});

Step 2 第2步

You php file looks like this: 您的php文件如下所示:

<?php 



  $array = json_decode($_POST['array']);
    print_r($array); //for debugging purposes only

     $response = array();
     if(isset($array[$blah])) 
        $response['reply']="Success";
    else 
        $response['reply']="Failure";

   echo json_encode($response);

Step 3 第三步

The success function 成功功能

success: function(data) {
        console.log(data.reply);
        alert(data.reply);
    }

You are already using " json " as dataType, so you shouldn't apply 'stringify' operation on your data. 您已经使用“ json ”作为dataType,因此您不应在数据上应用'stringify'操作。

Instead of request_arr: JSON.stringify(request) , can you try request_arr: request directly? 可以代替request_arr: JSON.stringify(request)来尝试request_arr: request直接request_arr: request吗?

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

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