将AJAX响应设置为Javascript变量

时间:2015-04-15 20:24:42

标签: javascript php ajax

我正在开发一个Javascript游戏,我正在尝试让它在游戏完全启动之前从我的数据库中加载随机选择的图像。

我正在使用ajax调用,该调用使用php脚本从我的数据库中的表中选择一个随机图像地址,然后将此图像地址回显给Javascript。

我想将此图片地址放在img.src =

之后的空格中

要做到这一点,我试图将ajax响应转换为一个变量,然后我可以放在img.src =之后,这样每次重新加载游戏时,都会进行一次新的ajax调用,并且随机选择的图片链接将在img.src =之后放置 (然后游戏使用img.src =)。

以下是我正在尝试的代码和评论:

//declaring a variable called “ajaxResponse” – this is what the ajax response will be attached to:

var ajaxResponse;

//a function containing the ajax call which returns the image address as its response:

function getRandomPicture() {
    $.ajax({
     url: 'picturerandomizer.php',
    data: "",
    dataType: 'json',
    success: function(response){ 
//attaching the response to the variable created at the start:
           ajaxResponse = response;
    }});
};

//this is where game code is, including the definition of ``img.src``, which I’m trying to define here as the ajaxResponse variable.

img.src = ajaxResponse;

目前没有将图像加载到游戏中(游戏启动但是图像应该位于空白处)。我想我的订单做错了吗? 我想我需要启动ajax调用,然后将游戏代码放在ajax调用的成功函数中。这样,随机图像将始终在游戏加载之前定义,但我不确定如何做到这一点。

如果ajax调用失败,那么我仍然希望启动游戏,但使用静态定义的img src,例如:

img.src = 'image001.jpg';

我真的很感激任何人对正确实现此代码的方法的建议。非常感谢提前!

0 个答案:

没有答案
相关问题