【问题标题】:How to call external PHP file in AJAX如何在 AJAX 中调用外部 PHP 文件
【发布时间】:2012-05-19 19:33:07
【问题描述】:

我有代码可以检查 test.php 文件中的用户名和密码。

但是当我调用这个 ajax 时,它总是显示用户名和密码错误的警报。
谁能告诉我哪里出错了?

$.ajax({
    type: "GET",
    url: 'http://externalurl/external/test.php',
    contentType: "text/html",
    data: 'uname=' + uname + '&pass=' + pass,
    success: function (data) {
        if (data == 'success') {
            alert('success');
        } else {
            alert('Wrong user name and password.Please try again');
        }
    }
});

【问题讨论】:

  • “我哪里出错了?” => 您正在使用 GET 发送密码。
  • 在 Firebug 或 Chrome 的开发工具中检查网络控制台,看看实际响应是什么。还有,詹姆斯所说的
  • 而且您没有使用data 的对象,这会导致某些字符出现问题。请改用data: {uname: uname, pass: pass}
  • @ThiefMaster : 我用过这个data: {uname: uname, pass: pass} 但还是同样的问题

标签: php javascript ajax


【解决方案1】:
$.ajax({
    type: "GET",
    url: 'test.php',
dataType: 'jsonp',
    contentType: "text/html",
    crossDomain:'true',
    data: {uname: "admin", pass: "admin"},
    success: function (json) {
        //process the json here.
    }
});

您对 ajax 的 data 字段使用了不正确的格式。

不,Javascript 通常不允许您通过 ajax 从外部服务器访问数据。它会给出

Origin http://externalhost 不允许 访问控制允许来源。

编辑:

不过,您可以设置crossDomaindataType:'jsonp' 从外部服务器获取JSON 数据。

【讨论】:

  • 现在它在萤火虫网络窗口中显示响应但不提醒它
  • alert(data);。即success: function (json) { alert(json) }
  • @Kunal !!你已经做了是什么意思。它在提醒什么?除非您从 PHP 返回 JSON 数据,否则它不会发出任何警报。
  • 表示我已经尝试过这段代码:alert(data); . ie, success: function (json) { alert(json) } 但仍然警告没有显示响应正在进入萤火虫网络窗口,即是和否
  • 这是因为 Javascript 不允许您从外部服务器访问非 JSON 数据。你根本不读书吗?使用 JSON 从服务器响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多