开发者

JSON with php and Jquery

开发者 https://www.devze.com 2023-01-15 13:35 出处:网络
I like to work with JSON and jquery. When I test the script offline on localhost it works fine, but when I change this json file to a server it doens\'t work al all

I like to work with JSON and jquery. When I test the script offline on localhost it works fine, but when I change this json file to a server it doens't work al all

    jQuery(function($) {

    $.ajax
    ({
        type: "GET",
        url: "test.php",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: companySearchSuccess,
        error: onError
    });



开发者_C百科function companySearchSuccess(json)
{
  alert("stap1");
var select = $('#city-list');

                $.each(json, function(k, v) {
                        var option = $('<option />');

                        option.attr('value', v)
                              .html(v)
                              .appendTo(select);
                });

}

function onError(m){
alert("Fout is: "+m);
}

});

This works fine,

but this one not:

  jQuery(function($) {

    $.ajax
    ({
        type: "GET",
        url: "http://www.example.com/test.php",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: companySearchSuccess,
        error: onError
    });



function companySearchSuccess(json)
{
  alert("stap1");
var select = $('#city-list');

                $.each(json, function(k, v) {
                        var option = $('<option />');

                        option.attr('value', v)
                              .html(v)
                              .appendTo(select);
                });

}

function onError(m){
alert("Fout is: "+m);
}

});

The error is: object xmlhttprequest>

Please help me


If you are running your app on localhost, and try to point your xml http request at another domain, you are violating the same origin policy and the browser won't actually do the request.

I am aware of 2 options:

1) Use jsonp. obviously the target server has to support jsonp
2) If you control the target domain/server, in your dev configuration make the protocol, domain, port match. This is the case where you can deploy a version of the server on localhost.

0

精彩评论

暂无评论...
验证码 换一张
取 消