手机端跨域的两种方式,如何连到电脑端的服务器接口
/**
一:js直接跨域提交(这个看上去像ajax,然后利用jsonP进行跨域,注意url写法)
**/
这个方法要注意的就是跨到服务端的方法以后,jsonP的那个回调函数是怎么回事,怎么把result数据成功返回来。
Model.prototype.loginBtn1 = function(event){
var data_loginData = this.comp("loginData");
$.ajax({
type: "post",
url: "http://127.0.0.1:9001/mobile/LoginService.po?event=ByJsonp",
dataType: "jsonp",
jsonp:'jsonp_callback',
data: {
loginName: this.comp("userName").val(),
loginPWD: this.comp("pwd").val()
},
success: function (json) {
if(json.isPass=="YES"){
//把获取的参数写到loginData中
data_loginData.setValue("userName",json.userName);
data_loginData.setValue("loginName",json.loginName);
data_loginData.setValue("userOrgan",json.userOrgan);
var params = {
data : {
loginData : data_loginData.getCurrentRow().toJson()
}
};
justep.Shell.showPage('index',params);
}else{
alert("账号不存在或异常,请重新登录");
}
}
});
};
/**
二:action跨域提交访问外部接口
**/
这种方式就是通过action调baas层的java类里面的方法,在里面用httpClient来实现跨域。来一段完整的java代码:
public static JSONObject loginAuthenticate2(JSONObject params, ActionContext context) throws SQLException, NamingException, java.sql.SQLException {String loginName = params.getString("loginName");String loginPWD = params.getString("loginPWD");//String registrationId = params.getString("registrationId");System.out.println("loginName: "+loginName);System.out.println("loginPWD: "+loginPWD);//System.out.println("registrationId: "+registrationId);JSONObject result = null;// 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost("http://127.0.0.1:9001/mobile/LoginService.po"); // 创建参数队列 Listformparams = new ArrayList();
formparams.add(new BasicNameValuePair("loginName",loginName));
formparams.add(new BasicNameValuePair("loginPWD",loginPWD));
//formparams.add(new BasicNameValuePair("registrationId",registrationId));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "UTF-8");//得到返回的String信息(json)
System.out.println("Response content: " + resultStr);
result = JSONObject.parseObject(resultStr);
return result;
}
} catch (JSONException e){
}finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}