简体   繁体   中英

Write jquery.ajax from existing javascript

I found this article: http://msdn.microsoft.com/en-us/library/dd251073.aspx

How could I write 'get' request using jquery.ajax?

您可以使用.get()方法。

http://api.jquery.com/jQuery.get/

Or just use the regular $.ajax() method (http://api.jquery.com/jQuery.ajax/), which defaults to a GET request.

It depends on whether Bing's API respects the standard ?callback=function method for specifying JSONP callbacks, but if so, then this simplified version of the Search() function should do it:

// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
        var requestStr = "http://api.bing.net/json.aspx?"

        // Common request fields (required)
        + "AppId=" + AppId
        + "&Query=Mispeling words is a common ocurrence."
        + "&Sources=Spell"

        // Common request fields (optional)
        + "&Version=2.0"
        + "&Market=en-us"
        + "&Options=EnableHighlighting"

        $.getJSON(requestStr, SearchCompleted);
}

Keep in mind that neither approach is directly triggering a GET, like you might be used to in AJAX requests to a local server using XMLHttpRequest.

To circumvent the cross-domain restriction on XHR, JSONP works by injecting a new script element into your document which then causes the browser to load (via GET) and execute that remote script. That remote script's contents are a single function call to your callback function, with the entire JSON payload as its parameter.


If that doesn't work, including those Bing-specific callback options should work fine in conjunction with jQuery:

// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
        var requestStr = "http://api.bing.net/json.aspx?"

        // Common request fields (required)
        + "AppId=" + AppId
        + "&Query=Mispeling words is a common ocurrence."
        + "&Sources=Spell"

        // Common request fields (optional)
        + "&Version=2.0"
        + "&Market=en-us"
        + "&Options=EnableHighlighting"

        // JSON-specific request fields (optional)
        + "&JsonType=callback"
        + "&JsonCallback=SearchCompleted";

        $.getJSON(requestStr);
}

Keep in mind that, at this point (and somewhat before), you aren't really using jQuery itself for much at all. Even though $.getJSON() or $.ajax() or $.get() seem like they're doing something more powerful than the MSDN example, jQuery is going to do exactly the same thing in this case (inject a script element with its src pointed at requestStr ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM