Ho letto la maggior parte delle domande SA relative a questo problema, ma nessuno ha risolto il mio problema.Errore Ajax Parse quando si restituisce un array da PHP
Il seguente codice passa un array JavaScript a PHP5. Questo funziona bene, ma quando torno un array PHP al codice ajax, un
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
}
});
L'array stringata passato è
["jQuery Translator","Hello World"]
PHP
EDIT
Il codice PHP completo è:
<?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);
}
}
?>
Il xhr.responseText è
"["<h1>jQuery Traductor<\/h1>"]["<p>Hola mundo<\/p>"]"
che non assomiglia a me JSON. Non sono un esperto di PHP5, ma sospetto che non sto riempiendo correttamente la matrice. Qualsiasi aiuto è apprezzato.
fare un 'var_export ($ tradotto);' invece di 'echo json_encode ($ tradotto);' e dopo i risultati, per favore. –
Grazie Tomas, le informazioni restituite. è: Dettagli: parsererror Errore: SyntaxError: token imprevisto un array (0 => ' jQuery Traductor',) array (0 => 'Hola mundo',) –
Potremmo vedere più codice php? Sembra che 'echo json_encode ($ tradotto);' sia in esecuzione due volte. Questo è l'unico modo per produrre una stringa composta da due jsonArray che sono insieme: "[...] [...]". –