doucheng1891 2013-02-01 14:07
浏览 91

Json调用JSON.parse:意外结束数据

I've been looking around stackoverflow for the answer to my problem but I can't seem to find why this is happening.

I've created a webserver which returns a JSON object:

http://213.125.101.19/api.php?function=test

After that i created an HTML file with the following javascript to call the JSON using Ajax

<script language="javascript" type="text/javascript">
    <!-- 
    //Browser Support Code
    function ajaxCall(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }

        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var response = ajaxRequest.responseText;
                obj = JSON.parse(response);
                console.log(obj);

                if(response.indexOf("Fatal error")>=0){
                    alert('Error, Try again.');
                }else{
                    document.getElementById("response").value = response;               
                }                 

            }   
        }


            ajaxRequest.open("GET", "http://213.125.101.19/api.php?function=test", true);
            ajaxRequest.send(null); 
    }
    </script>

When I run this code, my Firebug returns

"SyntaxError: JSON.parse: unexpected end of data obj = JSON.parse(response);"

If I run my JSON trough a validator, everything seems to be fine.

Any ideas how to fix this?

Kind Regards, Luuk

  • 写回答

2条回答 默认 最新

  • drci47425 2013-02-01 14:44
    关注

    JSON looks simple enough. I guess there's something wrong with the call or the return value.

    Check status and responseType as well

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            console.log('status=' + ajaxRequest.status +
                        ', statusText=' + ajaxRequest.statusText +
                        ', responseType=' + ajaxRequest.responseType +
                        ', responseText=' + ajaxRequest.responseText);
    ...
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器