Bagus Javas
Bagus Javas

Reputation: 123

How to send AJAX with dataType as script?

im trying to create own POST request. Here is my function:

function sendPost(o) {
    var h = new XMLHttpRequest();
    h.onreadystatechange = requestComplete;

    function requestComplete() {
        if ( h.readyState === 4 ) {
            if ( h.status === 200 ) {
                if ( o.done ) {
                    o.done(h.responseText);
                }
            } else {
                if ( o.fail ) {
                    o.fail(h.responseText);
                }
            }
        }
    }

    h.open('POST', o.url, true);
    h.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    h.send(o.data);
}

Everything is OK, but im confused, how to set its dataType to script, like in jQuery:

$.ajax({
    url: 'someurl.php',
    type: 'POST',
    dataType: 'script' // <-- how to do this?
});

Upvotes: 0

Views: 5193

Answers (1)

Quentin
Quentin

Reputation: 943571

dataType has very little to do with sending Ajax requests. It is primarily about what jQuery does with the response.

From the documentation:

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

So there is some modification to do with sending here.

  1. Take o.data
  2. Get a timestamp from a new Date()
  3. Check (by looking at indexOf('?') if it has a query string already
  4. Append either ? or & to the URL followed by the time stamp

The rest is all about processing the response:

Evaluates the response as JavaScript

So:

eval(h.responseText);

This is all rather nasty though. Generally speaking, if you want to dynamically load a script, you are usually better off doing it by adding a <script> element to a page.

Upvotes: 2

Related Questions