作者:HVV_Ha8m | 来源:互联网 | 2023-08-06 17:56
ImcreatingaPhoneGapappforAndroid.Togetdatafromthe(remote)serverImakeaRESTcallusi
I'm creating a PhoneGap app for Android. To get data from the (remote) server I make a REST call using jQuery's $.ajax() function. There are a few things you must know:
我正在为Android开发一个PhoneGap应用。要从(远程)服务器获取数据,我使用jQuery的$.ajax()函数进行REST调用。有几件事你必须知道:
- Type of the call must be POST
- 调用类型必须是POST
- The server expects JSON data(at least username and password)
- 服务器需要JSON数据(至少是用户名和密码)
- The server sends back JSON data
- 服务器返回JSON数据
The code:
代码:
function makeCall(){
var url = "http://remote/server/rest/call";
var jsOnData='{"username":"'+$('#username').val()+'","password":"'+$('#password').val()+'"}';
$.ajax({
headers: {"Content-Type":"application/json; charset=UTF-8"},
type: "POST",
url: url,
data: jsonData,
dataType: "json",
success: succesFunction,
error: errorFunction
});
}
But, this doesn't work. When I use Firebug to see the servers response, there is nothing. With TcpTrace I can see the headers of the request. Instead of an expected POST method, there is an OPTIONS method, with some strange headers added.
但是,这是行不通的。当我使用Firebug查看服务器响应时,什么都没有。通过TcpTrace,我可以看到请求的头部。这里有一个选项方法,添加了一些奇怪的标题,而不是预期的POST方法。
OPTIONS /remote/server/rest/call HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: nl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache
I know it has something to do with doing cross-domain requests, but I don't know how to solve the problem. I tried a few things to fix it, but with no result:
我知道这与跨域请求有关,但我不知道如何解决这个问题。我尝试了一些方法来修复它,但是没有结果:
- Use 'jsonp' in stead of 'json'
- 使用“jsonp”而不是“json”
- Try to use Cross-Origin Resource Sharing (CORS)
- 尝试使用跨源资源共享(CORS)
The problem has also something to do with same origin policy, but this does not apply to the file:// protocol PhoneGap is using to load a local html file.
问题还与同源策略有关,但这并不适用于加载本地html文件的// / PhoneGap协议。
In my AndroidManifest.xml file, the option
在我的AndroidManifest。xml文件的选项
is set.
是集。
I'm trying to fix this for 2 days now, but no result till now. Is this even possible to do? Do you have any tips for me so I can move on?
我想把这个问题解决两天,但是到现在还没有结果。这可能吗?你有什么建议给我,这样我就可以继续了吗?
Thanks in advance!
提前谢谢!
5 个解决方案