繁体   English   中英

使用jquery或ajax或angular js获取json响应

[英]Get json response with jquery or ajax or angular js

早上好stackoverflow

我尝试从URL Click获取json响应,正如预期的那样,我在GoogleChrome中获得了Access-Control-Allow-Origin ,为了避免出现此问题,我切换到了FireFox,然后状态为-1并且数据为空。


$(document).ready(function () {
        var URL = "https://www.infojort.com/axs/search?q=marouani%20zied";
        console.log('------------------------');
        $.ajax({
            url: URL,
            dataType: 'application/json;charset=utf-8',
            success:function (data) {
                console.dir(data);
                console.log('yes');
            },
            complete:function () {
                console.log('yes');
            }
        })

        $.ajax({
            dataType: "application/json;charset=utf-8",
            url: URL,
            success: function (data) {
                console.dir(data);
            }
        });

        $.getJSON(URL, function (data) {
            var items = [];
            $.each(data, function (key, val) {
                items.push("<li id='" + key + "'>" + val + "</li>");
            });

            $("<ul/>", {
                "class": "my-new-list",
                html: items.join("")
            }).appendTo("body");
        });

注意 :

  • 我可以毫无问题地与邮递员联系。
  • 内容类型→application / json; charset = utf-8

我需要使用jquery,ajax或angularjs的解决方案。 谢谢大家

您的问题似乎与API有关,而不与JavaScript调用本身有关,我的意思是, 您正试图从Cross Origin调用API,并且出于安全原因,默认情况下不允许这样做,因此您必须启用Cross Origin在服务器中以便进行此类调用 https://spring.io/understanding/CORS

看一下,这是一个跨源调用(AngularJS中的Jquery):

$.ajax({
  type: 'POST',
  url: CTHelper.ApiUrl() + '/token',
  data: {
    grant_type: 'password',
    username: $scope.UserName,
    password: $scope.Password
  },
  success: function (result) {
    alert('OK');
  },
  error: function (result) {
    alert('Error');
  }
});

API必须允许CORS ,这是文件Startup.Auth.cs的一部分

[此示例使用AspNet Web Api,C#作为后端]

public void ConfigureAuth(IAppBuilder app) {
  ...
  app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  ...
}

Microsoft.Owin.Cors可以作为nuget包下载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM