2

I am trying to get a json file from my server. Until now, always I need a json file, it was got by ajax and a php file in server creates the json file.

Not I have a json file (X.json) with this structure:

{
"zona": [
    {
        "zona1": [
            {
                "lon": "a",
                "lat": "b"
            },
            {
                "lon": "aa",
                "lat": "bb"
            },
            {
                "lon": "aaa",
                "lat": "bbb"
            },
            {
                "lon": "aaaa",
                "lat": "bbbb"
            }
        ]
    },
    {
        "zona2": [
            {
                "lon": "c",
                "lat": "d"
            },
            {
                "lon": "cc",
                "lat": "dd"
            },
            {
                "lon": "ccc",
                "lat": "ddd"
            },
            {
                "lon": "cccc",
                "lat": "dddd"
            },
            {
                "lon": "ccccc",
                "lat": "ddddd"
            }
        ]
    }
]
}

And when I try the same way to get the file, I didn't get anything. I think maybe it is possible to add the file when I load the webpage like a javascript file. Or maybe with jsonp but I trid and also I got bad answer.

As json try, I used:

$.ajax({
        url: 'localhost/open/listaPuntosZona.json',
        type: 'GET',
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        jsonp: "callback",
        jsonpCallback: "jsonpCallbackfunction",
        error: function () {
            alert("Error in Jsonp");
        }
    });

function jsonpCallbackfunction(responseData) {
alert(responseData);    

}

Also I wrapped json file with: callback( jsonfile code)

And also, this other two tries:

$.ajax({ 
  url: 'localhost/open/listaPuntosZona.json', 
  type: 'get', 
  error: function(data){ }, 
  complete: function(data){ 

    data=jQuery.parseJSON(data); //do something with data

    alert(data.zona.zona1.length);
  }
});



$.getJSON('localhost/open/listaPuntosZona.json',function(jsonData){
    alert("hola");
    alert(jsonData);
});

I am using lampp to test the webpage.

Do I have to change something? I used jsonp in past but don't know what I am doing wrong now.

4

2 回答 2

1

首先,尝试使用$.getJSON()而不是普通的 $.ajax()。它将立即解决许多问题。

http://api.jquery.com/jQuery.getJSON/

其次,确保你的 json 文件格式完美,没有任何松散的字符和奇怪的空格。

还尝试将错误处理程序链接到您的 ajax 调用。在上面的 getJSON 文档中可用。

var jqxhr = $.getJSON("example.json").error(function() { alert("error"); });
// this is according to documentation, i cannot currently test this to work, sorry about that.
于 2012-07-18T10:31:28.943 回答
0

我知道这已经过时了,但如果其他人像我一样遇到这个问题,这就是我能够解决它的方法......

将以下行添加到.htaccess文件中...

Header set Access-Control-Allow-Origin "*"
于 2021-02-04T21:25:35.147 回答