jquery – 从PHP返回数组时的Ajax Parse错误

前端之家收集整理的这篇文章主要介绍了jquery – 从PHP返回数组时的Ajax Parse错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了关于这个问题的大部分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代码是:

<?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);

在$元素的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);
原文链接:https://www.f2er.com/jquery/176548.html

猜你在找的jQuery相关文章