Bartyk
Bartyk

Reputation: 89

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?

Upvotes: 0

Views: 112

Answers (3)

Dave Ward
Dave Ward

Reputation: 60580

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 srcpointed at requestStr).

Upvotes: 0

Ryan Olds
Ryan Olds

Reputation: 4847

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039100

You could use the .get() method.

Upvotes: 1

Related Questions