【问题标题】:Getting data from web service with JSON使用 JSON 从 Web 服务获取数据
【发布时间】:2016-03-22 20:00:32
【问题描述】:

谁能告诉我我的代码有什么问题?我认为这是一个语法错误,因为我对 Javascript/JSON 不是很熟悉。目前,这段代码什么都不做。这是学校项目;我的班级正在构建一个应用程序,该应用程序通过提供一个基于空闲时间/课程安排来预订活动的界面来连接用户。谢谢!

    <!DOCTYPE html> 
<html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#submit").click(function(){
        var url = "http://3920project.azurewebsites.net/api/activity/";
        //var email = "?email=" + getUrlVars();
        //var title = "?title=" + "girls";
        var title = "?title=" + getTitle();

        //alert(url + title);
        $.getJSON(url + title)
        // data: {title: $("#title").val()
        .done(function(res) {
            //alert("done");
            $.each(res, function(key, item) {
                var colID = $('<td>', {
                text: item.category
                });
                var colName = $('<td>', {
                    text: item.day + item.to + item.from
                });
                $('<tr>').append(colID, colName).appendTo($('#tblResult:last'));
            }); //end of each()
        }); //end of done()
    }); //end of click()
}); //end of ready()
function getTitle() {
    return document.getElementById('title').value;
}
</script>

<style type="text/css">
    body {
        font-family: arial;
    }

    th,
    td {
        margin: 0;
        text-align: center;
        border-collapse: collapse;
        outline: 1px solid #e3e3e3;
    }

    td {
        padding: 5px 10px;
    }

    th {
        background: #666;
        color: white;
        padding: 5px 10px;
    }
    td:hover {
        cursor: pointer;
        background: #666;
        color: white;
    }
</style>
<title>Activity Search</title>
</head>

<body>
<div class="app">
    Please enter activity:
    <br></br>
    <input type="text" id="title">
    <input type="submit" id="submit" value="Search" />
    <br></br>
</div>
<div>
    <h2>Activity TimeTable</h2>
    <table id="tblResult">
        <tr>
            <th>Activity</th>
            <th>Category</th>
        </tr>
    </table>
</div>
</body>

</html>

【问题讨论】:

  • 你用 chrome 开发工具检查 js 错误了吗?
  • 检查您的res。这是一个字符串。使用JSON.parse(res)创建对象
  • 我的同学有类似的任务,她没有使用 JSON.parse(res) 并且她的工作正常。我认为我的问题与 .click 函数有关,因为它是少数与她不同的事情之一,因为她不需要用户输入。
  • 您的文档中没有ID为title的输入。
  • @Wainage 当你使用.getJSON 时,它会自动解析它。这就是.get 和.getJSON 之间的区别。

标签: javascript html json api


【解决方案1】:

您确实有语法错误。如果您打开开发者控制台 (F12),您会在 Chrome 中看到 uncaught SyntaxError: Unexpected Token )。所以在那之前有些事情是错误的。

在这种情况下,并不是你有多余的),而是浏览器不明白如何阅读getJSON() 后面的内容。如果你注释掉data: {title: $(#title").val(),它会编译得很好。

在尝试解决语法错误时,您可能还需要记录一些结束标记。

$(document).ready(function() {
    $("#submit").click(function(){
        var url = "http://3920project.azurewebsites.net/api/activity/";
    //var email = "?email=" + getUrlVars();
    //var title = "?title=" + "girls";
    var title = "?title=" + getTitle();

    //alert(url + title);
    $.getJSON(url + title)
    // data: {title: $("#title").val()
    .done(function(res) {
        //alert("done");
        $.each(res, function(key, item) {
            var colID = $('<td>', {
                text: item.category
            });
            var colName = $('<td>', {
                text: item.day + item.to + item.from
            });
            $('<tr>').append(colID, colName).appendTo($('#tblResult:last'));
        }); //end of each()
    }); //end of done()
    }); //end of click()
}); //end of ready()

更新: 浏览代码的下一步是使用getTitle()。 @blex 在 cmets 中指出您没有 ID 为 Title 的元素。所以你得到stackoverflow.html:40 Uncaught TypeError: Cannot read property 'value' of null的控制台错误

更新 现在您已将输入中的 id 从 activity 更改为 title,事情提交正确,但是您有 XMLHttpRequest cannot load http://3920project.azurewebsites.net/api/activity/?title=test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 的控制台错误

这意味着您遇到了 CORS 问题(跨域资源共享)。 Here is an article to help understand that。您在发出请求时没有设置正确的标头标志,或者服务器没有将您的域列入白名单以发出请求。

【讨论】:

  • 哦。猜猜我在他这样做之前就开始发布我的答案。此外,当我开始时,没有任何答案。我想我打字比别人慢,哈。
  • @Tess 相应地更新了我的答案
  • @EnigmaRM 谢谢!另一个学生负责网络服务,所以我想我现在能做的就是修复它。
  • @Tess 很高兴我能帮上忙。听起来是个有趣的项目。而且非常有用:使用 ajax 从 API 请求数据。
【解决方案2】:

这是您的 getJSON 语句。对象数据: {title: $("#title").val() 不合适,缺少结束 } 并且也是多余的,因为您将标题参数附加到 URL。

$.getJSON(url + title)
    .done(function(res) {
        //alert("done");
        $.each(res, function(key, item) {
            var colID = $('<td>', {
                text: item.category
            });
            var colName = $('<td>', {
                text: item.day + item.to + item.from
            });
            $('<tr>').append(colID, colName).appendTo($('#tblResult:last'));
        });
    });

【讨论】:

    【解决方案3】:

    这是不正确的 - data: {title: $("#title").val()。在你的代码中试试这个:

    $("#submit").click(function(){
        var url = "http://3920project.azurewebsites.net/api/activity/";
        var title = "?title=" + getTitle();
        $.getJSON(url + title)
        .done(function(res) {
            // Your code here
        })
        .fail(function(err){
            // check error
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多