understanding XMLHttpRequest responses using this (or other javascript) functions?

◇◆丶佛笑我妖孽 提交于 2019-12-04 17:02:34

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!