从PHP返回数组时出现Ajax Parse错误

时间:2016-01-07 20:59:19

标签: jquery arrays ajax php-5.5

我已经阅读了关于这个问题的大部分SA问题,但没有一个能解决我的问题。

以下代码将JavaScript数组传递给PHP5。这工作正常,但当我将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专家,但怀疑我没有正确填充数组。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:4)

移动

  header('Content-type: application/json');
    var_export($translated);
<$>超出$ elements的范围。

在$ 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);