简体   繁体   English

从javascript发送json到php

[英]Send json from javascript to php

I have a page where users do some stuff and on selecting next, I want to redirect them to a php file, called "Step2.php" along with some JSON information. 我有一个页面,用户在其中做一些事情,然后选择下一步,我想将他们重定向到一个名为“ Step2.php”的php文件以及一些JSON信息。

I built my json string and it looks like this: 我建立了我的json字符串,它看起来像这样:

[{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image/jpeg","width":null,"height":null,"lastModified":1374852216000,"fileExtension":"jpg","orientation":1,"displayed":true,"attributes":[{"title":"Name: ","value":"IMG_20130726_182336.jpg"},{"title":"Date: ","value":"no date"}]}]

Now, I sent it trough jquery POST like this: 现在,我通过jQuery POST发送了它,如下所示:

jsonData = JSON.stringify(serializableAttributes);
    console.log(jsonData);
    $.ajax({
        type: 'POST',
        url: 'Step2.php',
        data: {"jsonData" : jsonData},
        success: function(msg) {
            console.log("Json Sent! " +msg);
            window.location("")
        },
        error: function(request,msg){
            console.log("Error : " + msg);
        }
    });

Question: Why I can`t receive anything in my Step2.php file? 问题: 为什么我在Step2.php文件中什么都收不到? Am I wrongly redirect user to that page? 我是否将用户错误地重定向到该页面?

Code in the Step2.php files looks like this: Step2.php文件中的代码如下所示:

if(isset($_POST["jsonData"])) {
    $json = $_POST["jsonData"];
    var_dump(json_decode($json, true));
} else {
    echo "NO";
}

It always shows NO. 它总是显示NO。

You can't do it like this. 你不能这样做。 That's not how AJAX and POST work. 那不是AJAX和POST的工作方式。

If you're simply going to Step2.php, try sending it to the page as part of the URL. 如果您只是要转到Step2.php,请尝试将其作为URL的一部分发送到页面。

Instead of your AJAX function, simply do: 只需执行以下操作即可代替您的AJAX函数:

var jsonData = [YOUR DATA]; 
window.location.href="Step2.php?json="+jsonData

Or if PHP created the JSON string, you could store it as a SESSION variable. 或者,如果PHP创建了JSON字符串,则可以将其存储为SESSION变量。

EDIT: To venture a bit further on the SESSION variable route... 编辑:要进一步冒险在SESSION可变路线上...

Have your AJAX script as it is now, but make a new PHP file. 现在拥有您的AJAX脚本,但是创建一个新的PHP文件。 In this example we'll call it foo.php. 在此示例中,我们将其称为foo.php。 Have your foo.php file setup like so: 像这样设置foo.php文件:

session_start();
if($_POST){
    if(isset($_POST['jsonData'])){
        $json = $_POST['jsonData'];
        $_SESSION['jsonData'] = $json;
        //CREATE A JSON RESPONSE INIDCATING SUCCESS
        echo '{ "success" : 1 }';
    }
}

Your SUCCESS function of the AJAX call could analyze the response for the success code. 您的AJAX调用的SUCCESS函数可以分析成功代码的响应。 If it's "1" redirect to the Step2.php page. 如果它是“ 1”,则重定向到Step2.php页面。

Just make sure that you're calling session_start() at the top of each page. 只要确保您在每个页面的顶部都调用session_start()即可。

Ok so I think you misunderstand how AJAX works. 好的,我想您会误解AJAX的工作原理。 You ajax request sends the json to you php and should then respond to it with the appropriate return, in your case a var_dump . 您的ajax请求将json发送给您的php,然后应以适当的返回值对其进行响应,在您的情况下为var_dump

This won't hold the json in the php at all and if you go and request the php file without the POST request you won't get anything else but the output "NO" as there is no POST data you are sending. 这根本不会将json保留在php中,如果您在没有POST请求的情况下请求php文件,则不会获得任何其他信息,但输出为“ NO”,因为您没有发送POST数据。

If you do want to send a json to you php you do what you are doing now and listen to the request responds which you can see in your inspector. 如果您确实想向php发送一个json,请执行您现在正在做的事情,并听取您在检查器中看到的请求响应。 I am not clear on what you ultimately want to do with the data so I don't know if this is the right way. 我不清楚您最终想对数据做什么,因此我不知道这是否是正确的方法。

You can post JSON to PHP 您可以将JSON发布到PHP

jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.post("Step2.php", { json: jsonData },  function(msg) {
  console.log("image name = " + msg);
});

PHP, you simply parse: PHP,您只需解析:

if(isset($_POST['json'])){
   $json = $_POST['json'];
   $data = json_decode($json);
   $image = $data[0];
   echo $image->name;

   $atributes = $image->attributes;
   foreach($atributes as $atrribute){
    //echo 'title '.$atribute->title;
   }
}

Try this code in my work: 在我的工作中尝试以下代码:

<?php
if(isset($_POST["jsonData"])) {
    $json = $_POST["jsonData"];
    $json = str_replace('\\', '', $json);
    var_dump(json_decode($json, true));
    print_r($json);
} else {
    echo "NO";
}
?>

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

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