【问题标题】:jQuery Ajax always returns 'object' [duplicate]jQuery Ajax 总是返回“对象”[重复]
【发布时间】:2026-02-21 02:50:01
【问题描述】:

我有一些使用 Prototype 验证表单的代码,但我想添加一个 jQuery ajax 函数来检查用户名是否已存在于数据库中。但是,jQuery 返回的值始终是一个对象,而不是用户名是否存在的布尔值。到目前为止,这是我的代码:

validation.js

//Using Prototype
Validation.addAllThese([

    ['validate-username', 'Username already exists. Please choose another one.', 
      function (v) {     //v is the value of the username field in the form.

        //Using jQuery
        var match = jQuery.ajax({
                        url: "/php/ajax/check_username_exists.php",
                        data: {username: v},
                        async: false
                    });
        return (match.responseText == v);

]);

check_username_exists.php

<?php
include '../library.php';
include '../config.php';

//Echo string username if matches
echo select_row("USERNAME", "members", "USERNAME='".$_GET['username']."'");
?>

我检查了 * 上的其他线程,包括 this one,但似乎没有一个可以解决问题。

谢谢

【问题讨论】:

  • 是的,jQuery.ajax 返回一个 jqXHR 对象。这就是它应该做的。
  • 那么如何在验证函数中返回data的值呢?
  • @Daniel 您无法从 ajax 回调中返回。任何依赖ajax调用结果的工作都必须在回调中完成
  • 没有“完成”选项,改用“成功”。
  • 你能告诉我们你的服务器端代码吗?我想也许你正在从服务器获取 JSON 数据。

标签: ajax jquery validation prototypejs


【解决方案1】:

好的,下面是解决方案代码:

var match = jQuery.ajax({
    url: "/php/ajax/check_username_exists.php",
    data: {username: v},
    async: false
});
return (match.responseText != v);

Return 在无效时应该是 false。因此,如果用户名存在并且应该是 false,我让它返回 true。从==!= 的简单更改解决了这个问题。

【讨论】: