Ajax 从 PHP 返回数组时出现解析错误
Ajax Parse Error when returning array from PHP
我已经阅读了有关此问题的大部分 SA 问题,但是 none 已经解决了我的问题。
以下代码将 JavaScript 数组传递给 PHP5。这工作正常,但是当我 return 一个 PHP 数组到 ajax 代码时,一个
parserror: unexpected token "[" is returned.
JS
$(function () {
translate($("h1,p"));
function translate(selection$) {
var elements = [];
for (i = 0; i < selection$.length; i++) {
elements.push(selection$.get(i).outerHTML);
}
var jString = JSON.stringify(elements);
$.ajax({
url: 'test.php',
type: 'post',
data: { 'data': jString },
cache: false,
dataType: 'json',
success: function (data, status) {
$("#after").append(data);
},
error: function (xhr, desc, err) {
alert("Details: " + desc + "\nError: " + err + "\n" + xhr.responseText);
}
}); // end ajax call
}
});
传递的字符串化数组为
["jQuery Translator","Hello World"]
PHP
编辑
完整的PHP代码是:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if('POST' == $_SERVER['REQUEST_METHOD'])
{
include 'HttpTranslator.php';
include 'AccessTokenAuthentication.php';
if (!empty($_POST['data'])) {
$elements = json_decode($_POST['data']);
}
$auth = new AccessTokenAuthentication();
$authHeader=$auth->authenticate();
$fromLanguage = "en";
$toLanguage = "es";
$contentType = 'text/html';
$category = 'general';
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
foreach ($elements as $element) {
$params = "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
//Get the curlResponse.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
$translated = array();
foreach((array)$xmlObj[0] as $val){
array_push($translated, $val);
}
header('Content-type: application/json');
var_export($translated);
}
}
?>
xhr.responseText是
"["<h1>jQuery Traductor<\/h1>"]["<p>Hola mundo<\/p>"]"
这对我来说不像 json。我不是 PHP5 专家,但怀疑我没有正确填充数组。感谢任何帮助。
移动
header('Content-type: application/json');
var_export($translated);
在 $elements 的 foreach 之外。
也在 $elements 的 foreach 之前初始化 $translated = array();
。
像这样:
$translated = array();
foreach ($elements as $element) {
$params = "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
//Get the curlResponse.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val){
array_push($translated, $val);
}
}
header('Content-type: application/json');
var_export($translated);
我已经阅读了有关此问题的大部分 SA 问题,但是 none 已经解决了我的问题。
以下代码将 JavaScript 数组传递给 PHP5。这工作正常,但是当我 return 一个 PHP 数组到 ajax 代码时,一个
parserror: unexpected token "[" is returned.
JS
$(function () {
translate($("h1,p"));
function translate(selection$) {
var elements = [];
for (i = 0; i < selection$.length; i++) {
elements.push(selection$.get(i).outerHTML);
}
var jString = JSON.stringify(elements);
$.ajax({
url: 'test.php',
type: 'post',
data: { 'data': jString },
cache: false,
dataType: 'json',
success: function (data, status) {
$("#after").append(data);
},
error: function (xhr, desc, err) {
alert("Details: " + desc + "\nError: " + err + "\n" + xhr.responseText);
}
}); // end ajax call
}
});
传递的字符串化数组为
["jQuery Translator","Hello World"]
PHP
编辑
完整的PHP代码是:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if('POST' == $_SERVER['REQUEST_METHOD'])
{
include 'HttpTranslator.php';
include 'AccessTokenAuthentication.php';
if (!empty($_POST['data'])) {
$elements = json_decode($_POST['data']);
}
$auth = new AccessTokenAuthentication();
$authHeader=$auth->authenticate();
$fromLanguage = "en";
$toLanguage = "es";
$contentType = 'text/html';
$category = 'general';
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
foreach ($elements as $element) {
$params = "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
//Get the curlResponse.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
$translated = array();
foreach((array)$xmlObj[0] as $val){
array_push($translated, $val);
}
header('Content-type: application/json');
var_export($translated);
}
}
?>
xhr.responseText是
"["<h1>jQuery Traductor<\/h1>"]["<p>Hola mundo<\/p>"]"
这对我来说不像 json。我不是 PHP5 专家,但怀疑我没有正确填充数组。感谢任何帮助。
移动
header('Content-type: application/json');
var_export($translated);
在 $elements 的 foreach 之外。
也在 $elements 的 foreach 之前初始化 $translated = array();
。
像这样:
$translated = array();
foreach ($elements as $element) {
$params = "text=".urlencode($element)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
//Get the curlResponse.
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val){
array_push($translated, $val);
}
}
header('Content-type: application/json');
var_export($translated);