0

我从 ajax 调用中得到未定义,而我通过的变量肯定存在。

这是我的 ajax 函数:

function setMessages(roomId, username, message){
    $.ajax({
        type: "get",
        url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
        data: { roomId:roomId, username:username, message:message },
        success: function(html) {
                  strReturn = html;
                }
        });
}

我的PHP:

<?php
$roomdId = $_GET['roomId'];
$username = $_GET['username'];
$message = $_GET['message'];


echo $username;
?>

调用ajax:

$(document).on("click", "#messageSubmit", function(){
    var username = window.localStorage["username"];
    var message = $("#message").val();
    alert(setMessages(roomId, username, message));
    alert(roomId + username + message);
});

第一个警报返回未定义。无论我使用哪个变量。第二个警报返回所有 3 个变量,就像它们应该的那样。所以它们确实存在。我为此使用phonegap,但它在桌面浏览器上也是如此。

4

3 回答 3

2

该函数不返回值,即使返回,ajax 也是异步的,因此您必须等到数据返回才能使用它:

function setMessages(roomId, username, message){
    return $.ajax({
        type: "get",
        url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
        data: { roomId:roomId, username:username, message:message }
    });
}

$(document).on("click", "#messageSubmit", function(){
    var username = window.localStorage["username"],
        message  = $("#message").val();

    setMessages(roomId, username, message).done(function(data) {
        alert(data);
    });
});
于 2013-06-06T20:21:16.220 回答
1

尝试:

function setMessages(roomId, username, message){
  var strReturn = '';

  $.ajax({
    type: "get",
    url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
    data: { roomId:roomId, username:username, message:message },
    success: function(html) {
              strReturn = html;
            },
    async: false
  });
  return strReturn;
}
于 2013-06-06T20:21:42.960 回答
0

尝试以下

function setMessages(roomId, username, message){
    return $.ajax({
        type: "get",
        url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
        data: { roomId:roomId, username:username, message:message },
        success: function(html) {
                  strReturn = html;
                }
        });
}


<?php
$roomdId = $_GET['roomId'];
$username = $_GET['username'];
$message = $_GET['message'];


echo $username;
?>


$(document).on("click", "#messageSubmit", function(){
    var username = window.localStorage["username"];
    var message = $("#message").val();
    setMessages(roomId, username, message).done(function (){
        alert(strReturn);
        alert(roomId + username + message);
    });
});
于 2013-06-06T20:23:21.907 回答