简体   繁体   中英

Not getting json response in ajax call

<html>
  <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script>
    function fn(){
      $.ajax({
        type:'GET',
        url: "http://www.enquiry.indianrail.gov.in/ntes/NTES",
        data: "action=getTrainForDate&trainNo=16649&trainStartDate=11/04/2014&t=1397216860215&18q1xp3lm5=1ptur1oxbz1i5vwea0u61397214250740",
        dataType: "json",
        success:function(data){
          alert(data);
        }
      });
    }   
</script>
  </head>
  <body>
    <a href="#" onclick="fn();"> hi </a>
  </body>
</html>

您请求的 URL 返回(function(){location.reload();})() ,它不是 JSON、JSONP 或任何形式的有用数据。

Just to update you need to use jsonp instead of json because you're going to get CORS error otherwise. Updated code is

$.ajax({
    type:'GET',
    url: "http://www.enquiry.indianrail.gov.in/ntes/NTES",
    data: {"action" : "getTrainForDate", "trainNo" : "16649", "trainStartDate" : "11/04/2014", "t" : "1397216860215", "18q1xp3lm5" : "1ptur1oxbz1i5vwea0u61397214250740"},
    dataType: "jsonp",
    success:function(data){
        alert(data);
    }
});

Note there's nothing wrong in your way of sending data as string, I just prefer object way. Now when you make a call you'll end up getting this message (and not data)

Resource interpreted as Script but transferred with MIME type text/plain: "http://www.enquiry.indianrail.gov.in/ntes/NTES?callback=jQuery2119973546624…1397216860215&18q1xp3lm5=1ptur1oxbz1i5vwea0u61397214250740&_=1397220999300".

This is where problem is. If you hit the formed URL, it'll give you JavaScript function as a response and no data. This is what you get as a response

(function(){location.reload();})()

I think, server expects unique token (identified by "18q1xp3lm5" : "1ptur1oxbz1i5vwea0u61397214250740" set), for each request. If condition is not met, it sends reload request to the browser.

Since the call is made through AJAX, it's not able reload the page, but due to reused token, there's no result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM