使用fetch出现unexpected end of input 解决方法

传统的ajax(即xmlhttprequest)由于使用叫复杂,于是js新推出了fetch来获取后台数据,无需引进jq的$.ajax,也可以使用promise的链式用法去处理回调地狱,着实很方便,在谷歌上已经全部兼容,其他浏览器兼容还需要进一步的优化,推荐文章:

https://segmentfault.com/a/1190000003810652

通过这篇文章,自己写了一个fetch和PHP去测试(获取手机号码的归属地):

php:

<?php
header("Access-Control-Allow-Origin:*");
// 响应类型
header('Access-Control-Allow-Methods:POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with, content-type');

function getKey($key, $default = "")
{
    return trim(isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);
}

$phone= getKey("phone");
if (!empty($phone)) {
    $menuInfo = file_get_contents("https://way.jd.com/jisuapi/query4?shouji=".$phone."&appkey=86d15a3db19f29dccae449f8426a8cb3");
    echo $menuInfo;
}

  js:

<script>
    
    fetch("http://fm.xiaofany.com/APIpage/phone.php", {
        method: "post",
        headers: new Headers({
            'Accept': 'application/json'
        }),
        body: JSON.stringify({"phone": 1393622322})
    }).then(res => res.json())
        .then(data => console.log(data))
        .catch(e=>console.log(`错误为${e}`))
</script>

  运行以后发生了如下错误:

json意外结束,查找了官方文档,发现在传值的时候做好使用URLSearchParams的方法来传值,更改一下:

 

 

<script>

    fetch("http://fm.xiaofany.com/APIpage/phone.php", {
        method: "post",
        headers: new Headers({
            'Accept': 'application/json'
        }),
        body: new URLSearchParams({"phone": 1393622322})
    }).then(res => res.json())
        .then(data => console.log(data))
        .catch(e=>console.log(`错误为${e}`))
</script>

  完美:

 

posted @ 2018-03-23 11:13  明明一颗大白菜  阅读(2254)  评论(1编辑  收藏  举报
<-- -->