jquery ajax从http url获取响应文本

发布于 2024-07-26 23:57:18 字数 383 浏览 10 评论 0原文

既不:

var response = $.ajax({
    type: "GET",   
    url: "http://www.google.de",   
    async: false,
    success : function() {
        alert (this);
    }
});

也不:

var response2 = $.get("http://www.google.de", function(data) {
    alert("Data Loaded: " + data);
});

给我一个物体。 如何访问 responseText

Neither:

var response = $.ajax({
    type: "GET",   
    url: "http://www.google.de",   
    async: false,
    success : function() {
        alert (this);
    }
});

Nor:

var response2 = $.get("http://www.google.de", function(data) {
    alert("Data Loaded: " + data);
});

give me an object. How do I get access to the responseText?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

魔法少女 2024-08-02 23:57:18

您只需像这样重写它:

var response = '';
$.ajax({ type: "GET",   
         url: "http://www.google.de",   
         async: false,
         success : function(text)
         {
             response = text;
         }
});

alert(response);

You simply must rewrite it like that:

var response = '';
$.ajax({ type: "GET",   
         url: "http://www.google.de",   
         async: false,
         success : function(text)
         {
             response = text;
         }
});

alert(response);
新雨望断虹 2024-08-02 23:57:18

正如 Karim 所说,除非服务器允许,否则跨域 ajax 无法工作。 在这种情况下,谷歌不会,但是,在很多情况下,有一个简单的技巧可以解决这个问题。 只需让您的本地服务器传递通过 HTTP 或 HTTPS 检索到的内容即可。

例如,如果您使用 PHP,您可以:

使用以下命令创建文件 web_root/ajax_responders/google.php:

<?php
  echo file_get_contents('http://www.google.de');
?>

然后更改代码以连接到该文件,而不是直接在 javascript 中连接到 Google 域:

var response = $.ajax({ type: "GET",   
                        url: "/ajax_responders/google.php",   
                        async: false
                      }).responseText;
alert(response);

As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.

For example, if you were using PHP, you could:

Create the file web_root/ajax_responders/google.php with:

<?php
  echo file_get_contents('http://www.google.de');
?>

And then alter your code to connect to that instead of to Google's domain directly in the javascript:

var response = $.ajax({ type: "GET",   
                        url: "/ajax_responders/google.php",   
                        async: false
                      }).responseText;
alert(response);
愿与i 2024-08-02 23:57:18

首先你必须下载一个JQuery插件来允许跨域请求。
在这里下载:https://github.com/padolsey/jQuery-Plugins/downloads

将名为 query.xdomainsajax.js 的文件导入到您的项目中,并将其包含在以下代码中:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

要以文本形式获取外部网页的 html,您可以编写以下内容:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});

First you have to download a JQuery plugin to allow Cross-domain requests.
Download it here: https://github.com/padolsey/jQuery-Plugins/downloads

Import the file called query.xdomainsajax.js into your project and include it with this code:

<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>

To get the html of an external web page in text form you can write this:

$.ajax({
    url: "http://www.website.com",
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
    }
});
深巷少女 2024-08-02 23:57:18

在 jquery ajax 函数中,成功回调签名是:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

根据您要求的数据类型,使用“dataType”参数,您将获得“data”参数。

来自文档:

dataType(字符串)默认值:智能猜测(xml 或 html)。
您期望从服务器返回的数据类型。 如果未指定,jQuery 将根据响应的 MIME 类型智能地将responseXML 或responseText 传递到您的成功回调。

可用的类型(以及作为成功回调的第一个参数传递的结果)是:

“xml”:返回可以通过 jQuery 处理的 XML 文档。

“html”:以纯文本形式返回 HTML; 包含的脚本标签在插入 DOM 时会被评估。

“script”:将响应评估为 JavaScript 并将其作为纯文本返回。 除非使用选项“cache”,否则禁用缓存。 注意:这会将 POST 转换为远程域请求的 GET。

“json”:将响应评估为 JSON 并返回 JavaScript 对象。

“jsonp”:使用 JSONP 加载 JSON 块。 会额外添加一个“?callback=?” 添加到 URL 末尾以指定回调。 (jQuery 1.2 中添加)

“text”:纯文本字符串。

请参阅http://docs.jquery.com/Ajax/jQuery.ajax#options

in jquery ajax functions, the success callback signature is:

function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}

depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.

from the docs:

dataType (String) Default: Intelligent Guess (xml or html).
The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.

The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript Object.

"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)

"text": A plain text string.

see http://docs.jquery.com/Ajax/jQuery.ajax#options

北城挽邺 2024-08-02 23:57:18

据我所知,允许您使用ajax跨域的唯一方法是JSONP(http: //ajaxian.com/archives/jsonp-json-with-padding)。

这里有一篇文章,发布了一些实现跨域ajax的各种技术(http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).

And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

乖乖兔^ω^ 2024-08-02 23:57:18

实际上,您可以使用 IE Firefox 发出跨域请求,请参阅以下概述: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit 和 IE8 也以某种方式支持它。

Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit and IE8 supports it as well in some fashion.

比忠 2024-08-02 23:57:18

由于 jQuery AJAX 请求如果跨域就会失败,因此您可以使用 cURL(在 PHP 中)设置代理服务器。

假设一个PHP文件responder.php有以下内容:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

你的AJAX请求应该发送到这个responder.php文件,以便它执行跨域请求。

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

累赘 2024-08-02 23:57:18

这个怎么样?

$.get(some-url, some-data, function(d, s, x){
    // d is text response data
    // s is text status
    // x is a XMLHttpRequest object
    // so... you can code like that:

    console.log(x.responseText);
})

享受! :)

How about this?

$.get(some-url, some-data, function(d, s, x){
    // d is text response data
    // s is text status
    // x is a XMLHttpRequest object
    // so... you can code like that:

    console.log(x.responseText);
})

Enjoy! :)

傲性难收 2024-08-02 23:57:18

这是非常旧的,但希望这对某人有帮助。 我正在发送回带有不同错误代码的响应,这是我发现的唯一可行的解​​决方案,

$.ajax({
    data: {
        "data": "mydata"
    },
    type: "POST",
    url: "myurl"
}).done(function(data){
    alert(data);
}).fail(function(data){
    alert(data.responseText)
});

因为 JQuery 已弃用 successerror 函数,因此您需要使用 donefail,并在 fail 时使用 data.responseText 访问数据,并且仅使用 >数据完成时。

This is super old, but hopefully this helps somebody. I'm sending responses with different error codes back and this is the only solution I've found that works in

$.ajax({
    data: {
        "data": "mydata"
    },
    type: "POST",
    url: "myurl"
}).done(function(data){
    alert(data);
}).fail(function(data){
    alert(data.responseText)
});

Since JQuery deprecated the success and error functions, it's you need to use done and fail, and access the data with data.responseText when in fail, and just with data when in done.

撩人痒 2024-08-02 23:57:18

尝试这个

alert( data['responseText'] );

try this

alert( data['responseText'] );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文