使用Ajax从外部文件调用JSON数据

时间:2016-08-01 06:05:08

标签: javascript jquery json ajax

我正在调用一个带有一些示例JSON代码的外部JS文件,当我尝试将示例json代码放入文件时,它会在“:”处抛出错误,但是当我使用在线工具验证时,它表示为有效的json。这段代码出了什么问题?

这是我的代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


  <script>
$(document).ready(function() {

    $('#click').click(function() {
        $.ajax({
            url: "json.js",
            method: "GET",
            dataType: 'application/json',
            contentType: "application/json",
             success: function(result){
                  console.log(result);
             },
             error:function() {
                 alert("Error")                  
             }
        });
    });
});
</script>

我的外部json.js

{
"data": [{      ------> throwing error at ":" as Syntax error on token ":", ; expected
    "Service": "INSTACC",

    "Create Date": "30-Jul-2016"


}, {
    "Service": "INSTACC",

    "Create Date": "30-Jul-2016"


}]

}

2 个答案:

答案 0 :(得分:0)

将文件类型更改为json,将dataType更改为&#34; json&#34;

// controller (site)
public function actionFoo($type) 
// rule
'site/foo<type:(\.xtn)>' => 'site/foo', //site/foo.xtn
'site/foo/<type:(\.xtn)>' => 'site/foo' //site/foo/xtn

答案 1 :(得分:0)

“application / json”不是dataType属性的有效值。将其更改为dataType:'json',

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MyDemo</title>
</head>
<body>
<button id="click">Click Me</button>

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function() {

        $('#click').click(function() {
            $.ajax({
                url: "json.js",
                method: "GET",
                dataType: 'json',
                contentType: "application/json",
                success: function(result){
                    console.log(result);
                },
                error:function(req, status, err) {
                    console.log(req);
                    console.log(status);
                    console.log(err);
                }
            });
        });
    });
</script>
</body>
</html>
相关问题