【发布时间】:2015-03-11 13:43:28
【问题描述】:
我正在尝试将 JSON 数据从 JavaScript 发布到 PHP。你可以这样做
Content-Type: application/json
或
Content-Type: application/x-www-form-urlencoded
两者都有效,但我很难让第一个工作。原因是我错过了内容类型为application/json时PHP脚本似乎运行了2次。
我很惊讶,想知道发生了什么事。谁能解释发生了什么以及如何处理它? (有一些相关的问题,但似乎没有一个答案观察到这种行为。)
这是我的测试代码。首先启动PHP内置服务器:
php.exe -S localhost:7000
然后在该目录中使用以下代码创建文件test1.php:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
function writeStdErr($msg) { $fh = fopen('php://stderr','a'); fwrite($fh, $msg); fclose($fh); }
writeStdErr("\n\nI am here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
$e = stripslashes(file_get_contents("php://input"));
writeStdErr("e=".$e."\n");
if (strlen($e) > 0) echo $e;
现在从网络浏览器控制台(我使用的是 Google Chrome)进行 ajax 调用:
function test1(j) {
url = "http://localhost:7000/test1.php";
type = "application/x-www-form-urlencoded";
if (j) type = "application/json";
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", type);
xhr.addEventListener("readystatechange", function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password)
}
});
var data = JSON.stringify({"email":"hey@mail.com","type":type});
xhr.send(data);
console.log("now sending >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", url, type);
}
test1(false)
控制台中的输出正是我所期望的:
I am here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
e={"email":"hey@mail.com","type":"application/x-www-form-urlencoded"}
现在改为使用applicaion/json 进行ajax 调用,即test1(true)。现在的输出是:
I am here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
e=
I am here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
e={"email":"hey@mail.com","type":"application/json"}
如您所见,PHP 代码已经运行了两次。并且第一次在php://input上没有输入。
为什么???这应该如何在 PHP 中处理?
这里借用部分代码:Sending a JSON to server and retrieving a JSON in return, without JQuery
以下是一些相关问题: Code to be run twice in Ajax request, Running curl twice in php, https://stackoverflow.com/questions/24373623/ajax-request-help-code-gets-created-twice, Ajax form submitting twice with Yii 2
而这个问题(这里投票最高的问题之一)当然是相关的,但对于 PHP 代码为什么会运行两次没有什么可说的:
【问题讨论】:
标签: javascript php ajax json xmlhttprequest