【问题标题】:How to make sure ajax is used or not? [duplicate]如何确定是否使用了ajax? [复制]
【发布时间】:2012-09-27 06:31:14
【问题描述】:

可能重复:
Detecting Ajax in PHP and making sure request was from my own website

我有一个上传图片的表格,我正在使用Ajaxform()

$('#uploadformimage').ajaxForm({

    beforeSend: function() {
         $(".progress").css("display","block");
         $("#response").html("");
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },
    complete: function(xhr) {
            $(".bar").css("width","100%");
            $(".percent").html("100%").delay("8000").parent().slideUp(1000);
            $("#response").html(xhr.responseText);

    }
}); 

这是我的 javascript 代码。我想知道server-side 表单是不是由 ajax 上传的? Javascript 可能在某些计算机上被禁用,所以我想显示一些不同的数据?

【问题讨论】:

标签: php jquery ajax


【解决方案1】:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest')
{
    // This is an AJAX request
}

【讨论】:

  • 感谢它完美运行?
【解决方案2】:

我构建了一个演示,这是结果

Request URL:http://localhost/test.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:32
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11
X-Requested-With:XMLHttpRequest

【讨论】:

  • 我在那里使用谷歌浏览器检查器,你可以看到 ajax 调用以及所有其他外部调用从客户的立场无论如何希望有所帮助
【解决方案3】:

你可以传递一个选项GET /foo?xhr=1

然后在 PHP $_GET['xhr']

【讨论】:

    【解决方案4】:

    假设不涉及 AJAX。

    Javascript/AJAX 所能做到的就是让用户体验优于竞争对手。

    那么,您为什么要关心图像,而这取决于上传图像的人。该人可能没有 Javascript,

    只要做到最低限度并添加花里胡哨!

    【讨论】:

    • 我只想显示用户上传的图像。在正常情况下,我正在回显 img src。
    【解决方案5】:

    您可以在 HTML 中使用<noscript> 标记来生成不同的 HTML,以便表单可以发布到不同的服务器端脚本或向表单添加隐藏字段。

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2010-09-13
      • 2017-03-28
      • 2011-06-12
      相关资源
      最近更新 更多