PhoneGap development offers theoretical benefits.However, because javascript is the hero and stored directly in the mobile phone, interacting with server data will cause a cross-domain access problem.
Of course, there must be a solution to this problem, otherwise, this hybrid APP model using PhoneGap and others will not have any value.
There are many options on the web, such as getting data, using Jsonp.
But what about submitting data?
First, you can do some configuration on the server side to allow cross-domain requests.For example, for Web sites developed with ASP.NET, you can modify web.config by adding:
web.config:
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer>
Then the client JS:
$(function () { $("#divHello").html("Hello PhoneGap"); forServer();}); var ashx = "http://10.69.25.132/test.ashx";function forServer(){ var xhr; xhr = new XMLHttpRequest(); if (xhr){ xhr.onerror = function(){alert("error");}; //xhr.timeout = 60000;//IE9 plus this property will error, for some reason, other versions are not tested xhr.ontimeout = function(){alert("overtime");}; xhr.onload = function(){ var data = $.parseJSON(xhr.responseText); $("#divData").html(data.data); }; xhr.open("post", ashx,true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("p1=guangzhou tianhe"); } else{ alert("Failed to create"); }}
Server-side test.ashx
public class test1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; context.Response.Charset = "utf-8"; string res = String.Format(@"{{""data"":""{0}""}}", context.Request.Form["p1"] ); context.Response.Write(res); } public bool IsReusable { get { return false; } } }
Summary of experience:
1. $.getJSON() mode, Chrome can, IE can not survive, in IE browser, press F12 to view, no connection specified.ashx, directly refused.Use XMLHttpRequest instead, and both browsers will accept it.Place it in the Android phone simulator to work properly
2. In the form of http://localhost:8088/test.ashx, which cannot be connected in the Android phone emulator, change to IP or domain name: http://192.168.10.1:8088/test.ashx
function getData(){ $.getJSON( ashx ,{"uid" : Date()} ,function(data) { $("#divData").html(data.data); });}