understanding XMLHttpRequest responses using this

2019-04-12 14:14发布

Is there anyway of getting iphone/iPad to access XMLHTTPRequests, i.e. ajax responses from a web page within UIWebView. I've tried a couple of solutions out there where the response url is changed so that the app can identify that it is indeed an ajax response.

I'm new to ajax but I'm keen to learn. I just wandered if anyone could tell me the correlation between responses from ajax and the receiving browser.

Getting it to work through the iOS's uiwebview would be an added bonus.

So far I'm trying

ajax_handler.js

var s_ajaxListener = new Object();
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
    window.location='mpAjaxHandler://' + this.url;
};

XMLHttpRequest.prototype.open = function(a,b) {
  if (!a) var a='';
  if (!b) var b='';
  s_ajaxListener.tempOpen.apply(this, arguments);
  s_ajaxListener.method = a;  
  s_ajaxListener.url = b;
  if (a.toLowerCase() == 'get') {
    s_ajaxListener.data = b.split('?');
    s_ajaxListener.data = s_ajaxListener.data[1];
  }
}

XMLHttpRequest.prototype.send = function(a,b) {
  if (!a) var a='';
  if (!b) var b='';
  s_ajaxListener.tempSend.apply(this, arguments);
  if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
  s_ajaxListener.callback();
}

Objective C

JSHandler = [[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"ajax_handler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil] retain];


- (void)webViewDidStartLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:JSHandler];
}

which I got from here, I don't understand how this javascript will allow me to later access ajax responses that are returned from the ajax script on the server

1条回答
2楼-- · 2019-04-12 15:08

I will try to give you a simple demo for this - your can check this tutorial for ajax - http://www.w3schools.com/ajax/default.asp

function ajax (url, onsuccess)
{
    var xhr = new XMLHttpRequest();

    xhr.open ("GET", url);
    xhr.send ();

    xhr.onreadystatechange = function (event)
    {
        //alert (xhr.responseText);
        try {
            switch (xhr.readyState) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    //alert (xhr.statusText);
                    //alert (onsuccess);
                    onsuccess (xhr.responseText, xhr.statusText, xhr.status);
                    break;
                default:
                    break;
            }
        }
        catch (e)
        {
        }
    }
}

// call back when ajax is done
function onSuccessCallback (data, statusText, status)
{
    //alert (data);
}

function fetchPage ()
{
    ajax ("http://your domain is here", onSuccessCallback);
}

Then you can use this on your code to call this function, this will trigger the ajax call, but the ajax is working in "asynchronous" model (if you don't specify it to sync), so you just trigger it, but will not get the response in this method -

[self.webview stringByEvaluatingJavaScriptFromString:@"fetchPage();"

So here is a trick for doing javascript callback notify your webview -

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    // check the request, if it's ajax callback, just return NO; other wise YES;
    NSURLRequest *request = [self.webview request];
    NSURL *url = [request URL];

    NSString *file = [url lastPathComponent];

    if ([file isEqualToString:@"ajaxcallback.htm"] == YES) {
        // that means the ajax call is done, so you can call this 
        NSString *result = [self.webview stringByEvaluatingJavaScriptFromString:@"getResponse ();"];

        // don't forget to stop loading this fake page
        return NO;
    }
}

Modify the callback function of ajax -

var response;

function onSuccessCallback (data, statusText, status)
{
    // store the data to global variable
    response = data;

    // trigger webview to load a new page, but actually stop loading in delegate
    window.location = "http://www.domain.com/ajaxcallback.htm";
}

// call this in your objective C code
function getResponse ()
{
    return response;
}
查看更多
登录 后发表回答