0

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?
});
3
  • 1
    what's wrong with jquery's ajax implementation? Commented Aug 15, 2013 at 5:16
  • It comes with the overhead of jQuery Commented Aug 15, 2013 at 5:25
  • nothing wrong with jQuery... im just forgotting eval(); Commented Aug 15, 2013 at 5:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, great answer... thank you very much! This is helpful! i use the method of eval(h.responseText);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.