成功的XMLHTTPREQUEST从PHP下载数组,javascript json.parse无法正确解析

时间:2014-05-19 00:44:17

标签: javascript php json xmlhttprequest

正如标题所说,我已成功通过json编码的XMLHTTPREQUEST下载数组。当我尝试解码它时,它只是失败,即没有任何反应。调用“xhr.onreadystatechange = display_data;”之后的所有document.write语句(在该功能的实际处理之后)无法工作。但是,将解析后的数组赋值给函数中元素的innerhtml。这是我正在使用的脚本......

这与mod发布的另一个问题不同,因为我正在使用不同的代码块。 Javascript,而不是其他使用的.ajax方法。

我正在寻找有关此代码的帮助,而不是其他使用的块。

    <script>  
        var xhr;
         if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE 8 and older
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } 
            xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); 
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
            xhr.send();
            xhr.onreadystatechange = display_data;
            var $phparray
            function display_data() {
             if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                //alert(xhr.responseText);     
                $phparray = xhr.responseText;
                document.getElementById("suggestion").innerHTML = $phparray;
              } else {
                //alert('There was a problem with the request.');
              }
             }
            }  
            document.getElementById("suggestion").innerHTML = $phparray;
            document.write("Length of phparray Array :" + $phparray.length + "<");  
            var output = JSON.parse($phparray, function (key,val) {
                if ( typeof val === 'string' ) {
                    // regular expression to remove extra white space
                    if ( val.indexOf('\n') !== -1 ) {
                        var re = /\s\s+/g;
                        return val.replace(re, ' ');
                    } else {
                        return val;
                    }
                }
                return val;
            } ); 
            document.write("Length of Array :" + $output.length + "<");
            for (var i=0; i < $output.length; i++)
                {
                    document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME;
                }  
    </script> 

如您所见,它是相当标准的代码。然而,这确实产生了以下结果

document.getElementById("suggestion").innerHTML = $phparray;

以下是该行生成的输出。

'{"MEMBER_NAME":"Helen G.","BUS_NAME":"Heritage Makers","BUS_IMAGE_PATH":"HMHelen_copy.jpg","MEMBER_BIO":"I am a mother of very busy four year old twins girls. I have always been a scrapbooker but needed to find an easier and faster way to get my memories and photos in my books. I discovered Heritage Makers and am now able to create beautiful books, canvases and cards digitally and shipped right to my door. I cant wait to share the power of story-booking with you!\""}'

如您所见,它是未解析的数组。

任何建议都将不胜感激。

谢谢!

0 个答案:

没有答案