将JavaScript对象传递给PHP无法正常工作 [英] passing JavaScript object to PHP not working

查看:48
本文介绍了将JavaScript对象传递给PHP无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 JSON.stringify()

JavaScript:

Javascript:

$('#save').on('click touch', function(){
    obj = {
        "1" : {
            "1" : "hey",
            "2" : "hay"
            },              
        "2" : {
            "1" : "hey",
            "2" : "hay"
            }
    }

    var json = JSON.stringify( obj );
    console.log(json)
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        success: function(data) {
            alert(data);
            $("p").text(data);
        }
    });
});

ajax.php:

<?php 
    $obj = json_decode($json);
    echo $obj;
?> 

但是此代码返回一个错误,指出未定义 $ json .我不知道为什么这不起作用.

But this code returns an error saying that $json is not defined. I have no idea why this is not working.

推荐答案

有2个问题.

  1. 您未随请求发送任何数据
  2. 这不是从PHP请求中获取值的方式

首先,添加此*:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : { json: json }, // <---------------------
    ...

*这行得通,只是因为jQuery实现会自动将任何非字符串数据参数转换为采用表单编码的查询字符串.请参见文档.

然后,在您的PHP中,您应该这样做:

Then, in your PHP, you should do:

$jsonStr = $_POST['json'];
$json = json_decode($jsonStr);


另一种可能的方式:


Another possible way:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : json , // <---------------------
    ...

这样,您的数据将不是有效的 form-urlencoded 输入,因此PHP不会将其解析为 $ _ POST ,但是您仍然可以获取其中的内容您的输入将执行以下操作:

This way, your data will not be a valid form-urlencoded input, so PHP will not parse it into $_POST, but you still can get the contents of your input doing this:

$jsonStr = file_get_contents("php://input");
$json = json_decode($jsonStr);

这篇关于将JavaScript对象传递给PHP无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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