Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法使用jquery从json文件获取数据_Jquery_Ajax_Json_Web Applications - Fatal编程技术网

无法使用jquery从json文件获取数据

无法使用jquery从json文件获取数据,jquery,ajax,json,web-applications,Jquery,Ajax,Json,Web Applications,目前,我正在进行一个项目,在这个项目中,我必须使用JQuery将信息从web API提取到web应用程序中 <script src="jquery-1.11.2.js"></script> <script src="jquery-1.11.2.min.js"></script> <script type="text/javascript"> $(document).ready(function () { jQuery.

目前,我正在进行一个项目,在这个项目中,我必须使用JQuery将信息从web API提取到web应用程序中

<script src="jquery-1.11.2.js"></script>
<script src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
        jQuery.support.cors = true;
        $("#btn").click(function () {
            $.ajax({
                url: "http://localhost:52227/api/Values",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    alert("hello");
                }
            });
        });
    });
</script>

$(文档).ready(函数(){
jQuery.support.cors=true;
$(“#btn”)。单击(函数(){
$.ajax({
url:“http://localhost:52227/api/Values",
键入:“获取”,
数据类型:“json”,
成功:功能(数据){
警惕(“你好”);
}
});
});
});



当我运行此应用程序时,它不会显示任何输出。

您提供的代码在语法上是正确的。get请求很可能失败,并且您没有为该请求提供错误函数。您可以像这样添加一个错误回调

$.ajax
(
{
    url: "http://localhost:52227/api/Values",
    type: "GET",
    dataType: "json",
    success: function (data) {
        alert("hello");
    },
    error: function (data) {
        alert("test");
    }
}
)
下面是一个JSFIDLE,展示了它的实际应用


如果您将此url放入浏览器
“http://localhost:52227/api/Values
屏幕显示了什么?我得到的是我的web api 2 pass用户的xml格式ok,所以它是xml,而不是JSONY,我得到的输出是xml将您的数据类型更改为
数据类型:“xml”“
并查看这是否有效,但我在这里遇到了错误(我在警报框中得到了测试):这段代码中的错误是什么???您可以控制台。记录返回对象以收集有关错误的一些信息,或者您可以在浏览器中打开开发人员工具并查看网络选项卡以了解有关错误的一些信息。我用console.log而不是警报更新了JSFIDLE:问题不在于他告诉jquery在返回xml时使用JSON吗?这很可能是根本问题,但上面的答案会让他知道如何在将来排除这些错误,因为--XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”——当我运行代码成功时:函数(数据){alert(data.UserName);}(其中用户名是我的属性),它给我的消息为“undefined”
$.ajax
(
{
    url: "http://localhost:52227/api/Values",
    type: "GET",
    dataType: "json",
    success: function (data) {
        alert("hello");
    },
    error: function (data) {
        alert("test");
    }
}
)