jQuery Get Request on HTTP URL

jQuery Get Request on HTTP URL

本文关键字:HTTP URL on Request Get jQuery      更新时间:2023-09-26

我最近尝试使用jQuery从URL获取一些响应。因此,我将jQuery API Get Request Tutorial的get请求示例复制到我的项目中并尝试运行它,但是我的调试消息告诉我,它不能再进一步了。我使用一个简单的请求尝试了javascript Ajax库,但它不起作用。

所以我问你,你能不能以某种方式帮助我。

这就是我所做的一切,但没有回应。

var url = "http://www.google.com";
$.get(url, function(data){

    alert("Data Loaded: " + data);
    });

我可能忘记包含ajax或jQuery库了吗?为了更好地理解,我有c和obj-c的经验,这就是为什么我认为缺少一个库。

在每个示例中,只有一个短网址,例如"test.php"。我的完整 HTTP 网址有误吗?

感谢您提前回答。

溴网卡

我提供了一个示例场景来帮助您入门:

<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script

这可能最好包含在外部 JS 文件中:

//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
  $.ajax({
  //The URL to process the request
    'url' : 'page.php',
  //The type of request, also known as the "method" in HTML forms
  //Can be 'GET' or 'POST'
    'type' : 'GET',
  //Any post-data/get-data parameters
  //This is optional
    'data' : {
      'paramater1' : 'value',
      'parameter2' : 'another value'
    },
  //The response from the server
    'success' : function(data) {
    //You can use any jQuery/JavaScript here!!!
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
});

您正在针对 ajax 请求达到同源策略。

简而言之,默认情况下,JS/Ajax 只允许在与提供 HTML 页面的同一域上触发请求。如果您打算在其他域上触发请求,它必须支持 JSONP 和/或设置Access-Control标头才能使其正常工作。如果这不是一个选项,那么您必须在服务器端创建一些代理并使用它(请注意,因为您可能会因使用机器人从其他站点窃取过多而被禁止)。

正如其他人所说,您无法访问另一台服务器上的文件。有一个黑客。如果您使用的是服务器端语言(我假设您是),您可以简单地执行以下操作:

http://myserver.com/google.php:

<?php
  echo get_file_contents('http://www.google.com');
?>

http://myserver.com/myscript.js

$.get('google.php',function(data){ console.log(data) });

这应该有效!

您只能从域/服务器访问页面