发送数组从JavaScript / jQuery的到PHP [英] Sending an array to php from JavaScript/jQuery

查看:104
本文介绍了发送数组从JavaScript / jQuery的到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  发送数据的阵列从PHP的JavaScript


我知道有很多这样的问题,但我发现,他们都不是明确的。

我有一个Ajax请求,像这样:

  $。阿贾克斯({
    键入:POST,
    网址:parse_array.php
    数据:数组=+阵列,
    数据类型:JSON
    成功:功能(数据){
        警报(data.reply);
    }
});

我怎么会派一个JavaScript数组的PHP文件,什么将是其解析为一个PHP数组的PHP是什么样子?

我使用JSON。


解决方案

第1步

  $。阿贾克斯({
    键入:POST,
    网址:parse_array.php
    数据:{数组:JSON.stringify(阵列)},
    数据类型:JSON
    成功:功能(数据){
        警报(data.reply);
    }
});

第2步

您的PHP文件看起来是这样的:

 < PHP  $阵列= json_de code($ _ POST ['阵']);
    的print_r($数组); //仅用于调试的目的     $响应=阵列();
     如果(使用isset($数组[$等等))
        $响应['回复'] =成功;
    其他
        $响应['回复'] =失败;   回声json_en code($响应);

第3步

成功函数

 成功:功能(数据){
        的console.log(data.reply);
        警报(data.reply);
    }

Possible Duplicate:
send arrays of data from php to javascript

I know there are many questions like this but I find that none of them are that clear.

I have an Ajax request like so:

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

How would I send a JavaScript array to a php file and what would be the php that parses it into a php array look like?

I am using JSON.

解决方案

Step 1

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

Step 2

You php file looks like this:

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

这篇关于发送数组从JavaScript / jQuery的到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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