duanhe6718 2013-06-06 20:17
浏览 112

从ajax调用获取未定义

I am getting undefined from an ajax call while the variables I pass through exist for sure.

This is my ajax function:

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;
                }
        });
}

My PHP:

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


echo $username;
?>

Calling ajax:

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

The first alert returns undefined. No matter which variable I use. The second alert returns all 3 variables like they are supposed to be. So they do exist for sure. I am using phonegap for this but it does the same on desktop browser.

  • 写回答

3条回答 默认 最新

  • douren6035 2013-06-06 20:21
    关注

    The function does not return a value, and even if it did, ajax is async, so you'll have to wait until the data is returned before you can use it :

    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);
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿