[英]jQuery Mobile -> Load content from external server
I am working on a seemingly basic mobile app (first). 我正在开发一个看似基本的移动应用程序(第一个)。 But I want to enable the application to request information from our 'head' server.
但是我想使应用程序能够从“头”服务器请求信息。 To make sure it has the latest information.
确保它具有最新信息。
I'm currently running a jQuery script like this. 我目前正在运行这样的jQuery脚本。
$.ajax({
url: 'http://www.domain.com/list.php',
dataType: 'json',
crossDomain: true,
success: function(data) {
// Remove all content first
$(contentId +' li').remove();
// Load Data
$.each(data.items, function(index, list){
$(contentId).append('<li><a href="details.html?id=' + list.homeId + '" >' + list.name + '</a></li>\n');
});
// Reload View
$(contentId).listview('refresh');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: '+ jqXHR + textStatus + errorThrown);
}
});
And actually on that LIST.PHP file, it does return a JSON string. 实际上,在该LIST.PHP文件上,它确实返回JSON字符串。 But what I did for security was by adding this as a header
但是我为安全所做的就是将此添加为标题
header("Access-Control-Allow-Origin: *");
Or I could change * to a domain/url to add better security. 或者,我可以将*更改为域/ URL,以提高安全性。 But if I don't add that header() code in their, my javascript breaks and won't run properly.
但是,如果我没有在其中添加header()代码,我的JavaScript就会中断,并且无法正常运行。
I guess what i'm truly wondering is, am I doing this properly? 我想我真正想知道的是,我这样做是否正确? or is there a better way to do this?
还是有更好的方法来做到这一点? I have tried JSONP, but I can't seem to get that to work for cross domain.
我已经尝试过JSONP,但似乎无法将其用于跨域。
Is my solution sound? 我的解决方案听起来不错吗? or total crap?
还是总胡扯? Any thoughts or direction would be greatly appreciated!
任何想法或方向将不胜感激!
I think you should look into JSONP
. 我认为您应该研究
JSONP
。 It's not that hard. 没那么难。 On the client side, jQuery already handles it out of the box, just append a
?callback=?
在客户端,jQuery已经可以立即使用它,只需附加一个
?callback=?
to the URL. URL。 On the server, instead of just responding with JSON, eg:
在服务器上,而不只是用JSON响应,例如:
{
"foo": "bar"
}
Look for the query parameter callback
, and if it exists, wrap your JSON output in a function call with the name being the value of the callback parameter, so, for callback=foo
: 查找查询参数
callback
,如果存在,将JSON输出包装在一个函数调用中,其名称为callback参数的值,因此对于callback=foo
:
foo({
"foo": "bar"
})
When responding with JSONP, send Content-Type: text/javascript
. 使用JSONP响应时,发送
Content-Type: text/javascript
。 This should work without setting Access-Control-Allow-Origin
or anything like that. 这应该在不设置
Access-Control-Allow-Origin
或类似内容的情况下起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.