检索整个使用jQuery和JSONP域HTML [英] Retrieve html across domains using jQuery and JSONP

查看:137
本文介绍了检索整个使用jQuery和JSONP域HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有输出的HTML &LT一行简单的一种形式; A HREF =链接>在LINK< / A>

我可以附加到URL如 http://site.com数据直接访问过程/form.asp?sample=100

由于这是跨域去(一个子域),我试图做到这一点使用JSONP。我第一次尝试用数据类型的JSON,但我仍然得到一个403禁止的。下面是我想用JSONP但这是各种乱了,并返回与此%5Bobject%20Object%5D追加到它。我想这是我如何试图将数据追加到一个问题的错误网址是什么?

  $ j.getJSON({
        键入:POST,
        网址:http://site.com/form.asp,
        数据:为了='+ ordervalue,
        的contentType:应用/ JSON的;字符集= UTF-8,
        数据类型:JSONP
        成功:函数(响应){
            警报(响应);
        }
    });
 

解决方案

JSONP不工作就是这样,你不发送JSON在所有的,你发送的HTML。

JSONP是一个严格的GET请求(通过创建了一个<脚本> 标记),您不能跨域的的获取结果回来...它只是不这样的。该方法JSONP的工作原理是它基本上其加入到你的页面:

 <脚本类型=文/ JavaScript的SRC =htt​​p://site.com/form.asp?order=something&callback=myFunc>< /脚本>
 

......这种反应必须是有效的JavaScript,它通常是这样的:

  myFunc的({关键:值...的数据,等等...});
 

它不包括获取HTML工作,它只是抛出一个语法错误,这个限制是的非常的故意和部分安全模块的地方(的同源策略

I have a form that outputs one simple line of html <a href="link">A LINK</a>

I can access the process directly with data appended to the url like http://site.com/form.asp?sample=100

Because this is going across domains (to a subdomain) I am trying to do this using JSONP. I first tried it with datatype json but I was still getting a 403 forbidden. Here is what I am trying with JSONP but this is all kinds of messed up and returns an error with this %5Bobject%20Object%5D" appended to it. I guess it is a problem with how I am trying to append the data to the url ?

$j.getJSON({
        type: 'POST',
        url: 'http://site.com/form.asp',
        data: 'order=' + ordervalue,
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        success: function(response) {
            alert(response);
        }
    });

解决方案

JSONP doesn't work like this, you're not sending JSON at all, you're sending HTML.

JSONP is strictly a GET request (made by creating a <script> tag), you cannot POST cross-domain and get the result back...it just doesn't work that way. The way JSONP works is it basically adds this to your page:

<script type="text/javascript" src="http://site.com/form.asp?order=something&callback=myFunc"></script>

....that response has to be valid JavaScript, typically it looks like:

myFunc({ "key": "value"...data, etc... });

It doesn't work for fetching HTML, it just throws a syntax error, this limitation is very intentional, and part of the security blocks in place (part of the same origin policy).

这篇关于检索整个使用jQuery和JSONP域HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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