douzao2992 2016-07-11 15:55
浏览 101
已采纳

XAMPP返回错误“JSON输入的意外结束”

I'm trying to use XAMPP with the following snippets:

The php:

<?php
$api_endpoint = 'https://api.forecast.io/forecast';
$api_key = 'my-api-key';
$url = $api_endpoint . '/' . $api_key . '/' . '37.8267,-122.423';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
echo json_encode($curl_response);
?>

The JSON itself looks like this:

{
latitude: 37.8267,
longitude: -122.423,
timezone: "America/Los_Angeles",
offset: -7,
currently: {
time: 1468248192,
summary: "Clear",
icon: "clear-day"
}
}

The javascript:

$(document).ready(function(){
$('#myButton').click(function(e){
e.preventDefault();
$('#myButton').fadeOut(300);
$.ajax({
  url: 'php/forecast.php',
  type: 'GET',
  dataType: 'json',
  success: function(data, status) {
      $('#content').html(data.latitude);
  },
  error: function(xhr, desc, err) {
    console.log(xhr);
    console.log("Details: " + desc + "
Error:" + err);
  }
});
});
});

I works perfectly on a live server, but when using XAMPP I keep getting the error Unexpected end of JSON input. Has anyone ran into this issue before with XAMPP? Any thoughts on what could be causing this?

  • 写回答

1条回答 默认 最新

  • dongzhent208577 2016-07-11 17:43
    关注

    Your code is fine and the json format is okay (if your code works in a real web server there's no reason to think the json is wrong). First of all, you don't need to do json_encode because you know you'll get a json response from forecast.io server. And your ajax already contains dataType: 'json'.

    The main problem here is that you are calling an endpoint provided over SSL (https://api.forecast.io), so your php server in your local XAMPP needs to use a CA (Certificate authority) to make sure the communication is valid.

    Generally XAMPP does not give you this for free. So, download the latest CA pem file from http://curl.haxx.se/docs/caextract.html and save it in C:\xampp\php\cacert.pem; then edit C:\xampp\php\php.ini and look for curl.cainfo, uncomment it and add =C:\xampp\php\cacert.pem to have curl.cainfo = C:\xampp\php\cacert.pem.

    Save the file and restart your local Apache server. That's enough.

    As a further note, to debug your php code, you may think to echo eventual errors. So add something like this in your php code:

    $curl_response = curl_exec($curl);
    if(curl_error($curl)) {
        echo 'error:' . curl_error($curl);
    }
    curl_close($curl);
    echo ($curl_response);
    

    and make sure you can catch the error string in your ajax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换