Reputation: 1265
In my phone gap project I need to access json / html data from a remote server .I tried with Xmlhttprequest,but it is not working.It will be helpful if somebody helped me.Thanks in advance.
Note: I am using phone gap with php
Upvotes: 0
Views: 2285
Reputation: 6029
Here is some code that I use for making connections to a REST style API (uses jquery):
var api = {
connection: {
baseUrl: 'your_domain.tld',
apiUrl: '/some_path/'
},
initialize: function() {
api.setupAjaxDefaults();
},
setupAjaxDefaults: function() {
var headers = {
'Accept': "application/json; encoding='utf-8'",
'Content-Type': "application/json; encoding='utf-8'"
};
$.ajaxSetup({
headers: headers,
dataType: 'json',
crossDomain: true
});
},
testCall: function(data) {
api.ajaxGet( someMethod, data, aSuccessCallback, anErrorCallback );
},
ajaxGet: function(methodName, data, successCallback, errorCallback) {
$.ajax({
url: api.connection.baseUrl + api.connection.apiUrl + methodName,
data: data,
cache: false,
type: 'GET',
success: function(result, status, xhr) {
if ($.isFunction(successCallback)) {
successCallback(result);
}
},
error: function() {
if ($.isFunction(errorCallback)) {
errorCallback();
}
}
});
},
ajaxGetCached: function(methodName, data, successCallback, errorCallback) {
$.ajax({
url: api.connection.baseUrl + api.connection.apiUrl + methodName,
data: data,
type: 'GET',
success: function(result, status, xhr) {
if ($.isFunction(successCallback)) {
successCallback(result);
}
},
error: function() {
if ($.isFunction(errorCallback)) {
errorCallback();
}
}
});
}
};
To use this, You first call api.initialize();
Then to make a call (example of testCall in place above):
api.testCall(someApiMethod, { data: someData, moreData: evenMore });
Upvotes: 1