【问题标题】:Using HTTP GET with JQuery将 HTTP GET 与 JQuery 一起使用
【发布时间】:2013-06-15 07:24:47
【问题描述】:

我正在尝试使用 GET HTTP cal,我收到了使用高级 REST 客户端 (Chrome plugin) 的请求,但无法让它在 JQuery 中工作。

根据this thread 的建议,我设置了以下内容:

$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
      url: 'https://api2.panopta.com/v2/monitoring_node/41',
      type: 'GET',
      dataType: 'json',
      success: function() { alert('hello!'); },
      error: function() { alert('boo!'); },
      beforeSend: setHeader
  });
});
function setHeader(xhr) {
    //extra stuff from REST CLIENT
    xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });

这是我想要得到的输出(使用 REST 客户端成功)

{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}

我只想能够从该 JSON 中访问 name 变量并将其传递给我的函数。在我试图弄清楚如何创建一个对象之前,我想至少让上面的代码工作,这样我就可以成功地调用这个名字,比如.append(object.name)

我刚开始学习 JQuery,这是我的第一篇文章,如果我没有包含足够的细节,非常抱歉。

【问题讨论】:

标签: html jquery


【解决方案1】:

您不能将 ajax 调用应用于其他域。您可以通过 curl()file_get_content(url) 使用服务器到服务器调用来解决问题,然后对您的脚本进行 js 调用。

首先制作一个php文件,它会调用服务器注意如果你想使用file_get_contents你应该在你的php.ini中允许url_fopen:

myProxy.php

<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>

你的 js 应该调用你的 PHP,所以你有解决方法相同的域策略:

$.ajax({
      url: 'myProxy.php',
      type: 'GET',
      dataType: 'json',
      success: function() { alert('hello!'); },
      error: function() { alert('boo!'); },
      beforeSend: setHeader
  });
});

【讨论】:

    【解决方案2】:

    我不确定您的 api 信息是否正确,但我认为您需要做的主要事情是更改为 jsonp 而不是 json,因为 musa 提到的来源政策相同。

    以下 JS 小提琴“有效”,但请求未在服务器授权:http://jsfiddle.net/cf8S9/

    $(document).ready(function() {
    $('#button').click(function(){
    $.ajax({
          url: 'https://api2.panopta.com/v2/monitoring_node/41',
          type: 'GET',
          dataType: 'jsonp',
          success: function() { alert('hello!'); },
          error: function() { console.log(arguments);alert('boo!'); },
          beforeSend: setHeader
      });
    });
    function setHeader(xhr) {
        //extra stuff from REST CLIENT
        xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
    } });
    

    【讨论】:

    • 根据question,无法使用带有自定义标头(我的授权密钥)的 JSONP,感谢您向我介绍 jsfiddle!
    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多