简体   繁体   English

如何将ajax中的javascript关联数组传递给php文件

[英]how to pass a javascript associative array in ajax to php file

How can i pass data (associative array) to php file. 如何将数据(关联数组)传递给php文件。

 function ajax(url,data,callback)
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                xmlhttp.onreadystatechange = function() {
                    if ( xmlhttp.readyState === 4 ) {
                        callback( xmlhttp.responseText );
                    }
                }
            }
            xmlhttp.open("POST",url,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(data);
        }

The way i read this, you are in javascript, and you have a javascript object (javascript does not have associative arrays, just arrays and objects). 我读这个的方式,你是在javascript中,你有一个javascript对象(javascript没有关联数组,只有数组和对象)。 So, whatever data you have, you need to turn it into a string and sent it via POST or GET to your php script. 因此,无论您拥有什么数据,都需要将其转换为字符串并通过POST或GET将其发送到您的php脚本。 I would recommend including JSON3 as a polyfill to ensure you will have JSON.stringify on your page (for cross-browserness). 我建议将JSON3作为polyfill包含,以确保您的页面上有JSON.stringify (用于跨浏览器)。 Code will be something like this: 代码将是这样的:

var data = {
    someData: 'data',
    moreData: [
        'blah',
        'bleh'
    ]
};

var stringData = JSON.stringify( data );

// using jquery ajax for brevity (http://api.jquery.com/jQuery.ajax/)
$.ajax({
  type: "POST",
  url: "your-php-script.php",
  data: { data: stringData }
});

Now your php script can snag that string and turn it back into json itself: 现在你的php脚本可以阻止该字符串并将其转换回json本身:

<?php
    $dataString = $_POST['data'];
    $data = json_decode($dataString);

Hopefully this is what you were looking for. 希望这是你想要的。 Cheers! 干杯!

You can use PHP's JSON functions to achieve this. 您可以使用PHP的JSON函数来实现此目的。 It will encode/decode arrays into a notation that javascript can handle. 它会将数组编码/解码为javascript可以处理的符号。

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

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