简体   繁体   English

Jsonp跨域Ajax

[英]Jsonp cross-domain ajax

I'm working on an application which use ajax call to get html from the server. 我正在使用ajax调用从服务器获取html的应用程序。 When I run it on the server, everything works fine. 当我在服务器上运行它时,一切正常。

But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error. 但是,当我在本地主机上运行时,出现“ Access-Control-Allow-Origin”错误。 I looked arround and it seems like using jsonp could be the solution. 我看着周围,似乎使用jsonp可能是解决方案。

So, my ajax call looks like that: 因此,我的ajax调用看起来像这样:

$.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    type: 'GET',
    success: function(data){
        // should put the data in a div
    },
    error: function(){
        //do some stuff with errors
    }
});

I get html from the server, but I always have this error: 我从服务器获取html,但始终出现此错误:

Uncaught SyntaxError: Unexpected token < 

Is there a way to wrap the jsonp response in html? 有没有办法将jsonp响应包装为html?

Thanks! 谢谢!

You can't use JSONP to grab an HTML document. 您不能使用JSONP来获取HTML文档。 You need to wrap your HTML in a JavaScript variable. 您需要将HTML包装在JavaScript变量中。 JSONP has some very specific requirements to make it work properly, including a callback function/attribute. JSONP有一些非常特定的要求才能使其正常运行,包括回调函数/属性。 If you're not in control of the server hosting the target page, you won't be able to make it work. 如果您不受托管目标页面的服务器的控制,则将无法使其正常运行。 This is a security precaution to prevent a random page from being able to steal your personal information from sites you're logged into via an AJAX call. 这是一项安全预防措施,可防止随机页面能够通过AJAX调用从您登录的网站上窃取您的个人信息。

UPDATE 更新

I read your question more thoroughly. 我更彻底地阅读了您的问题。 It sounds like your problem is that you're in a development environment that doesn't have the resource in question. 听起来您的问题是您所处的开发环境中没有相关资源。 JSONP isn't the answer because it's a lot of trouble to get running just to make your page work in development. JSONP并不是解决方案,因为仅运行以使页面在开发中运行就很麻烦。 You should create a local copy of the target HTML and grab it using a relative or server-absolute URL such as "/the/page/i/need.html" instead of "http://myserver.com/the/page/i/need.html" 您应该创建目标HTML的本地副本,并使用相对或服务器绝对URL(例如"/the/page/i/need.html"而不是"http://myserver.com/the/page/i/need.html"

If you want to get the data by jsonp, then the server side need to support jsonp. 如果要通过jsonp获取数据,则服务器端需要支持jsonp。

There is no way just change the dataType to get the data. 不能仅更改dataType来获取数据。

If the server side doesn't support jsonp, then you need to make a proxy in your localhost. 如果服务器端不支持jsonp,则需要在本地主机中创建代理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM