Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ajax()解析器错误_Javascript_Jquery_Json_Parse Error - Fatal编程技术网

Javascript ajax()解析器错误

Javascript ajax()解析器错误,javascript,jquery,json,parse-error,Javascript,Jquery,Json,Parse Error,当我尝试通过以下方式从获取JSON时: 我得到:parserror;200; 未定义;未调用jquery162*************** 但是使用来自的JSON可以很好地工作。 两者都是有效的JSON格式。那么这个错误是关于什么的呢 [更新] @3 Gima,我已经在asp.net中实现了这一点,它运行良好: $.ajax({ type: "POST", url: "WebService.asmx/GetTestData", data: "{}", conte

当我尝试通过以下方式从获取JSON时:

我得到:
parserror;200; 未定义;未调用jquery162***************

但是使用来自的JSON可以很好地工作。 两者都是有效的JSON格式。那么这个错误是关于什么的呢

[更新]

@3 Gima,我已经在asp.net中实现了这一点,它运行良好:

$.ajax({
    type: "POST",
    url: "WebService.asmx/GetTestData",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        alert(result.d);
    }
});
WebService.asmx:

[WebMethod]
public string GetTestData()
{
    try
    {
        var req = System.Net.HttpWebRequest.Create("http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json");
        using (var resp = req.GetResponse())
        using (var stream = resp.GetResponseStream())
        using (var reader = new System.IO.StreamReader(stream))
        return reader.ReadToEnd();
    }
    catch (Exception) { return null; }
}

这是因为您告诉jQuery您期望的是,而不是,返回。但回报是JSON。JSON-P的命名错误得可怕,命名方式令人困惑不已。这是一种通过
脚本
标记将数据传输到函数的约定。相反,JSON是一种数据格式

JSON示例:

{"foo": "bar"}
JSON-p的示例:

yourCallback({"foo": "bar"});

JSON-p之所以有效,是因为JSON是JavaScript文字符号的子集。JSON-P只不过是一种承诺,如果您告诉服务您要调用的函数名(通常通过在请求中放入
回调
参数),响应将以
函数名(数据)
的形式出现,其中
数据
将是“JSON”(或者更常见的是,一个JavaScript文本,这可能不是完全相同的东西)。您需要在
脚本
标记的
src
(jQuery为您做的)中使用一个JSON-P URL,以绕过阻止ajax请求从源文件以外的源文件请求数据的问题(除非服务器支持且您的浏览器也支持)。

如果服务器不支持跨域请求,您可以:

  • 创建服务器端代理
  • 向代理发送ajax请求,代理将从服务获取
    json
    ,然后
  • 返回响应,然后您可以操纵它
  • 在php中,您可以这样做

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
    $("#btn").click(function(){
    alert("abt to do ajax");
    
    $.ajax({
    url:'proxy.php',
    type:"POST",
    data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
    success:function(data){
    alert("success");
    alert(data);
    }    
    });    
    });   
    });
    </script>
    
    php包含以下代码

    <?php
    
    if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
    $data = file_get_contents($_POST['geturl']);
    print $data;
    }
    
    ?>
    
    
    
    然后像这样对代理执行ajax请求

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
    $("#btn").click(function(){
    alert("abt to do ajax");
    
    $.ajax({
    url:'proxy.php',
    type:"POST",
    data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
    success:function(data){
    alert("success");
    alert(data);
    }    
    });    
    });   
    });
    </script>
    
    
    $(函数(){
    $(“#btn”)。单击(函数(){
    警报(“abt to do ajax”);
    $.ajax({
    url:'proxy.php',
    类型:“POST”,
    数据:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
    成功:功能(数据){
    警惕(“成功”);
    警报(数据);
    }    
    });    
    });   
    });
    

    经过尝试和测试,我得到了json响应…

    最后我找到了解决方案。首先,Web服务或页面中的webmethods对我不起作用,它总是返回xml,在本地工作正常,但在像godaddy这样的服务提供器中不起作用

    我的解决方案是在.net中创建一个
    .ahsx
    ,这是一个处理程序,并使用传递jsonp的jquery回调函数包装内容,它就可以工作了

    [System.Web.Script.Services.ScriptService]
    public class HandlerExterno : IHttpHandler
    {
        string respuesta = string.Empty;
    
        public void ProcessRequest ( HttpContext context )
        {
    
    
           string  calls=  context.Request.QueryString["callback"].ToString();
    
             respuesta = ObtenerRespuesta();
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write( calls +"("+    respuesta +")");
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
        [System.Web.Services.WebMethod]
        private string ObtenerRespuesta ()
        {
    
    
    
            System.Web.Script.Serialization.JavaScriptSerializer j = new System.Web.Script.Serialization.JavaScriptSerializer();
    
    
            Employee[] e = new Employee[2];
            e[0] = new Employee();
            e[0].Name = "Ajay Singh";
            e[0].Company = "Birlasoft Ltd.";
            e[0].Address = "LosAngeles California";
            e[0].Phone = "1204675";
            e[0].Country = "US";
            e[1] = new Employee();
            e[1].Name = "Ajay Singh";
            e[1].Company = "Birlasoft Ltd.";
            e[1].Address = "D-195 Sector Noida";
            e[1].Phone = "1204675";
            e[1].Country = "India";
    
            respuesta = j.Serialize(e).ToString();
            return respuesta;
    
        }
    
    }//class
    
    public class Employee
    {
        public string Name
        {
            get;
            set;
        }
        public string Company
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Phone
        {
            get;
            set;
        }
        public string Country
        {
            get;
            set;
        }
    }
    
    下面是jquery的调用:

    $(document).ready(function () {
        $.ajax({
            // url: "http://www.wookmark.com/api/json",
            url: 'http://www.gjgsoftware.com/handlerexterno.ashx',
            dataType: "jsonp",
    
    
            success: function (data) {
                alert(data[0].Name);
            },
            error: function (data, status, errorThrown) {
                $('p').html(status + ">>  " + errorThrown);
            }
        });
    });
    
    而且效果很好


    Gabriel

    顺便说一句,这个API似乎不支持JSON-p(我只找到了这个:)。哦,我明白了。嗯,如果我把数据类型设置为JSON,它也不起作用。@Stack:它不会起作用,除非你调用它的页面是在
    API-v3.deezer.com
    ,因为SOP(请参阅答案中的链接)哦,我明白了。我现在明白了。谢谢。你可以参考。async:false很重要。