我已经阅读了关于这个问题的大部分SA问题,但没有一个能解决我的问题.
以下代码将JavaScript数组传递给PHP5.这工作正常,但当我将PHP数组返回到ajax代码时,a
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代码是:
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是
"["jQuery Traductor<\/h1>"]["
Hola mundo<\/p>"]"
这对我来说不像是json.我不是PHP5专家,但怀疑我没有正确填充数组.任何帮助表示赞赏.