0

Here is my script:

$.ajax({ 
    type: "Get", 
    url: "Sample.js",
    datatype: 'json', 
    data: JSON.stringify({ key:key }), 
    success: function (data) { 
        var sample = data.name; 
        $("#html").html(sample); 
    }, 
    error: function () {
        alert("Error"); 
    }
});

This is my Sample.js file:

{ "name": "user" }

When I run this code I get a blank screen. This is my script using getJSON():

$.getJSON("Sample.js", function (data) { 
    var sample = data.name; 
    $("#html").html(sample); 
})

This produces "user" perfectly. What is the problem with $.ajax code?

4

3 回答 3

1

As the jQuery documentation states:

$.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});

Try modifying the dataType param.

于 2013-09-30T10:22:50.797 回答
1

In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.

于 2013-09-30T10:32:45.150 回答
0

change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/

Remove JSON.Stringify and change Get to GET

$.ajax(
   { type: "GET", 
     url: "Sample.js", 
     dataType: "json",
     data: {key:key }, 
     success: function (data) 
      { var sample = data.name; $("#html").html(sample); }, 
     error: function () { alert("Error"); }}
);
于 2013-09-30T10:20:46.833 回答