JSON解析怪时$。员额()Ajax错误 [英] Strange $.post() AJAX error when parsing JSON

查看:123
本文介绍了JSON解析怪时$。员额()Ajax错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 $。交

面对这个奇怪的错误

工作

  $(#附加视频)。点击(函数(){
    VAR URL = $(#新的视频网址)VAL()。
    $('#装载机)显示()。
    $。员额(BASE_URL +表格/教练/ get_url.php,网址:{url:URL,BASE_URL:BASE_URL},功能(数据){
        警报(数据);
                    $('#装载机)隐藏()。
    });
});
 

上面的一张​​code,显示我的JSON数组我使用一个PHP文件接收,并且这里也显示了标题字段,并隐藏了装载机图像。

但是当我警报(data.title),它表明我不确定。更过,当我添加数据类型JSON来 $。交

不起作用

  $(#附加视频)。点击(函数(){
    VAR URL = $(#新的视频网址)VAL()。
    $('#装载机)显示()。
    $。员额(BASE_URL +表格/教练/ get_url.php,网址:{url:URL,BASE_URL:BASE_URL},功能(数据){
        警报(数据);
                    $('#装载机)隐藏()。
    },JSON); //添加数据类型在这里。
});
 

这既不警报什么也不会隐藏加载图像。我也试过,

  $(#附加视频)。点击(函数(){
    VAR URL = $(#新的视频网址)VAL()。
    $('#装载机)显示()。
    $。员额(BASE_URL +表格/教练/ get_url.php,网址:{url:URL,BASE_URL:BASE_URL},功能(数据){
        jQuery.parseJSON(数据);
                    警报(data.title);
                    $('#装载机)隐藏()。
    });
});
 

上面的一个了没有任何警报,也不隐藏加载器。然后,我试过这一个了,没有什么做了。

  $(#附加视频)。点击(函数(){
    VAR URL = $(#新的视频网址)VAL()。
    $('#装载机)显示()。
    $。员额(BASE_URL +表格/教练/ get_url.php,网址:{url:URL,BASE_URL:BASE_URL},功能(数据){
        jQuery.parseJSON(数据); //尝试没有这一点。
                    警报(数据['标题']);
                    $('#装载机)隐藏()。
    });
});
 

最奇怪的是,我有previously使用JSON,因为我已经证明在第二脚本(满分4),并且工作正常。我的JS控制台太不显示任何错误或警告。我在做什么错在这里?如何访问数据的标题字段?

如果这会有所帮助,这里是我如何发送JSON阵列,

  $ JSON =阵列(标题=> $标题,嵌入=> $嵌入,降序=> $递减,持续时间=> $时间,日期=> $日期);
的print_r(json_en code($ JSON));
 

我真的AP preciate如果有人能指出错误,告诉我​​为什么我的脚本失败,类似的功能在其他js文件的工作。

这里是我的数据,由服务器返回,

  

{称号:苏恩拉哈海娜涂Aashiqui 2全歌歌词|   阿迪蒂亚罗伊·卡普尔,Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"$p$psenting   全曲\孙拉哈海娜涂\与电影\歌词Aashiqui 2 \   通过T系列电影和放大器产生的; Vishesh电影,主演阿迪蒂亚罗伊·卡普尔,   施拉达·卡普尔在ANKIT蒂瓦里的声音。 \ñ\ nSong:苏恩RAHA   HAI \ nSinger:ANKIT TIWARI \ nMusic导演:ANKIT TIWARI \ nAssistant混合   工程师迈克尔 - 埃德温·皮莱\ nMixed和ERIC皮莱掌握   (孟买未来之声)\小芊:SANDEEP NATH \ n电影:AASHIQUI   2 \ nProducer:BHUSHAN KUMAR克尚KUAMR制片人:MUKESH BHATT
  \ nDirector:莫希特苏瑞\ nMusic标签:T系列\ñ\ nBuy从iTunes -   https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy   &放大器;和我们呆在一起连接! \ñ\ nSUBSCRIBE T系列渠道   无限的娱乐\ nhttp://www.youtube.com/tseries \ n \ nCircle公司   我们对G + \ nhttp://www.google.com/+tseriesmusic \ñ\ nLike我们   Facebook的\ nhttp://www.facebook.com/tseriesmusic \ñ\ nFollow   我们\ nhttp://www.twitter.com/_Tseries,持续时间:391,日期:2013年4月3日}

修改

这突然的工作..:0

  $(#附加视频)。点击(函数(){
    VAR URL = $(#新的视频网址)VAL()。
    $('#装载机)显示()。
    $。员额(BASE_URL +表格/教练/ get_url.php,网址:{url:URL,BASE_URL:BASE_URL},功能(数据){
            警报(data.desc);
            执行console.log(data.desc);
            $(#装载机)隐藏()。

    },JSON);
});
 

解决方案

在注释中,您提到这AJAX对应到YouTube API。

YouTube的博客在2012年宣布,他们将支持 CORS ,它使用服务器端头标志是兼容的浏览器跨preT为允许请求,否则将被禁止通过浏览器的安全同源,政策

假设,正如你所说的,第一个例子中的工作,第一个问题是为什么(后续)警报(data.title)失败?(我的编辑) 。如果您在控制台中键入警报(data.title),它会失败,因为范围 数据是它被定义为一个参数的回调函数,并在全球范围内数据是不确定的。如果你尝试通过数据全局范围不知何故,它仍然是不确定的,因为 $。交立即返回,之前的数据被取出,而仅仅是对请求排队,并设置您提供办理答复的回调函数。

第二个例子,其中明确规定了 $。员额 的dataType 参数JSON,可能会失败, CORS 的API,因为<一HREF =htt​​p://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type> JSON的MIME类型不允许被发送到服务器的Content-Type:简单的CORS请求 $交将据我只知道做没有preflight简单的请求。 $。阿贾克斯能做,如果正确地运用了更复杂的要求。

变通方法继续使用 $。交未使用 JSON 作为预期的数据类型,发送请求了作为表单数据,服务器可能会反正送你回去JSON如果这是API的说会发生,这可以被验证,而当测试code。

https://developer.mozilla.org/en-US/docs / HTTP / Access_control_CORS

  

简单的要求

     

一个简单的跨站点请求是指:

     

只有使用GET,HEAD或POST。

     

如果POST用于将数据发送到   服务器,发送给服务器与HTTP的内容类型的数据的   POST请求是应用程序的一个/ X WWW的形式,urlen codeD,   的multipart / form-data的,或者text / plain的。

注意应用程序/ JSON 没有做什么内容类型允许在一个列表简单的CORS请求

另请参见<一个href="http://stackoverflow.com/questions/5584923/a-cors-post-request-works-from-plain-javascript-but-why-not-with-jquery">A CORS POST请求的工作从简单的JavaScript,但为什么不使用jQuery?

I am facing this strange error in using $.post.

works

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();        
    });
});

The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.

But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,

doesn't work

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();        
    }, "json"); //Added datatype here.
});

This neither alerts anything nor does it hide the loader image. I also tried,

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);
                    alert(data.title);
                    $('#loader').hide();        
    });
});

The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);  //tried without this too.
                    alert(data['title']);
                    $('#loader').hide();        
    });
});

The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?

If this helps, here is how I send the json array,

$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));

I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.

here is my data, that is returned by server,

{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics | Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\" produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur, Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI (FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI 2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR Producer: MUKESH BHATT
\nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes - https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy & stay connected with us!! \n\nSUBSCRIBE T-Series channel for unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}

Edit

This worked suddenly.. :o

  $("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
            alert(data.desc);
            console.log(data.desc);
            $("#loader").hide();

    }, "json");
});

解决方案

In comments, you mention that this AJAX corresponds to a YouTube API.

YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.

Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ". If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined. If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.

The second example, which explicitly sets the $.post dataType parameter to 'json', may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.

The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.

From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Simple requests

A simple cross-site request is one that:

Only uses GET, HEAD or POST.

If POST is used to send data to the server, the Content-Type of the data sent to the server with the HTTP POST request is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.

See also A CORS POST request works from plain javascript, but why not with jQuery?

这篇关于JSON解析怪时$。员额()Ajax错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆