在jQuery中正确使用$ .post

时间:2010-08-27 15:32:22

标签: php javascript jquery ajax post

我有一个跨越一系列页面和脚本构建的网站,我正在尝试使用Ajax将它们链接在一起。有人告诉我发送回服务器的最简单方法是使用jQuery,所以我正在尝试,但我似乎无法让它工作。我的三个文件如下,有问题的方法是包含onclick()的行和文件3中的MySQL查询。

这是页面本身:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Penelope, Upgraded</title>

    <script type="text/javascript" src="jLaser.js"/>
    <script type="text/javascript" src="jquery.js"/>


    <?php

        require_once 'mysqlSheep.php';
        require_once 'background.php';

        $hour = date("G");
        $hour = mysql_real_escape_string($hour);

        mysql_query("INSERT INTO time( hour ) VALUES (".$hour.")
                    ON DUPLICATE KEY UPDATE hits = hits+1")
                    or die ("MySQL Error: ".mysql_error());
    ?>
</head>

<body id="<?php echo day() == 1 ? 'day' : 'night'; ?>">
    <button type="button"
            onclick="laser(); $.post('sheepDB.php', { vic: victim, num: numVics });">
    Activate Her Powers!
    </button>

    <div id="lasertext"></div>

    <p>Want to see how many things Queen Penelope <a href="http://www.queenofsheep.com/Sheep/victimlist.php">has decimated?</a></p>

</body>
</html>

这是.js脚本,其中包含我onclick()首先调用的一系列函数:

/*
 * Initialize laserState to 0
 * i.e. the laser is off.
 */
var laserState = 0;
var numVics;

/*
 * Function: laser
 * Called from button on jSheep.php
 *
 * If the laser is on, i.e. laserState = 0,
 * it calls laserOn(). Otherwise, it calls laserOff().
 *
 * @call laserOff() if laserState == 1
 * @call laserOn() if laserState == 0
 */
function laser()
{
    laserState ? laserOff() : laserOn();
}

/*
 * Function: laserOff
 * Called from function laser()
 *
 * Turns off the laser.
 * Sets laserState to 0,
 * prints a message about the laser being off,
 * and switches the image to the sheep minus the laser.
 */
function laserOff()
{
    laserState = 0;

    if ( document.getElementById("vartext") )
    {
        var textdiv = document.getElementById("lasertext");
        var para = document.getElementById("vartext");

        textdiv.removeChild(para);
    }

    if ( document.getElementById("nightlaser") )
    {
        var body = document.getElementById("nightlaser");

        body.setAttribute('id', 'night');
    }

    if ( document.getElementById("daylaser") )
    {
        body = document.getElementById("daylaser");

        body.setAttribute('id', 'day');
    }

    textdiv = document.getElementById("lasertext");
    para = document.createElement("p");
    var text = document.createTextNode("Queen Penelope has deactivated her lasers.");

    para.setAttribute("id", "vartext");
    para.appendChild(text);
    textdiv.appendChild(para);
}

/*
 * Function: laserOn
 * Called from function laser()
 *
 * Turns on the laser
 * Sets laserState to 1,
 * removes the text about the laser being off,
 * calls function selectVictim
 * and uses the returned value to call function zapVictim.
 *
 * @call selectVictim()
 * @call zapVictims()
 */
function laserOn()
{
    laserState = 1;

    if ( document.getElementById("vartext") )
    {
        var textdiv = document.getElementById("lasertext");
        var para = document.getElementById("vartext");

        textdiv.removeChild(para);
    }

    if ( document.getElementById("night") )
    {
        var body = document.getElementById("night");

        body.setAttribute('id', 'nightlaser');
    }

    if ( document.getElementById("day") )
    {
        body = document.getElementById("day");

        body.setAttribute('id', 'daylaser');
    }

    return selectVictim( function( victim ) {zapVictims(victim);} );
}

/*
 * Function: selectVictim
 * Called from function laserOn()
 *
 * Selects a random victim from a list of victims
 *
 * @return String: victim
 */
function selectVictim(callback)
{
    var vicString;
    var vicArray;
    var vicID;

    var params = "url=queenofsheep.com/Sheep/victims.php";
    var request = new ajaxRequest();

    request.open("POST", "victims.php", true);
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-Length", params.length);
    request.setRequestHeader("Connection", "close");

    request.send(params);

    request.onreadystatechange = function ()
    {
        if (this.readyState == 4)
        {
            if (this.status == 200)
            {
                if (this.responseText != null )
                {
                    vicString = this.responseText;
                    vicArray = JSON.parse(vicString);
                    vicID = Math.floor(Math.random() * (vicArray.length - 1));

                    if(callback)
                    {
                        callback(vicArray[vicID]);
                    }
                }
                else alert("Ajax error: No data received");
            }
            else alert("Ajax Error: " + this.statusText);
        }
    }
}

/*
 * Function: zapVictims
 * Called from function laserOn()
 *
 * @Arg String: victim
 *
 * Given the identifier of a victim,
 * generates a pseudorandom number of victims
 * to be zapped with the laser.
 * Then, it passes this number and the victim string
 * to a PHP script that updates the database values.
 */
function zapVictims( victim )
{
    numVics = Math.floor(Math.random() * 100) + 1;

    var textdiv = document.getElementById("lasertext");
    var para = document.createElement("p");
    var text = document.createTextNode("Queen Penelope has dissolved " + numVics + " " + victim + "!");

    para.setAttribute("id", "vartext");
    para.appendChild(text);
    textdiv.appendChild(para);
}

/*
 * Function: ajaxRequest
 * Called whenever external data is needed
 *
 * Tried to create a new XMLHttpRequest object
 * If it can't, attempts to correct for IE.
 * Finally, if it still can't, returns false.
 * Otherwise, it returns the created object.
 *
 * @return Boolean false
 * @return Object XMLHttpRequest
 * @return Object ActiveXObject
 */
function ajaxRequest()
    {
        try
        {
            var request = new XMLHttpRequest();
        }
        catch(e1)
        {
            try
            {
                request = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e2)
            {
                try
                {
                    request = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(e3)
                {
                    return false;
                }
            }
        }
        return request;
    }

最后,应该接收POST数据的脚本:

<?php

require_once 'mysqlSheep.php';

$numVics = mysql_real_escape_string($_POST["numVics"]);
$vic = mysql_real_escape_string($_POST["vic"]);

mysql_query("
            UPDATE victims
            SET amount=amount+".$numVIcs."
            WHERE victim='".$vic."'"
           );

&GT;

我哪里错了?来自Javascript文件(包含在页面中)的变量是否不适用于onclick?除了第三个文件中的MySQL update外,一切都正常。

1 个答案:

答案 0 :(得分:0)

一些事情:

  • 在哪里定义变量“victim”(在你的第一个文件中,当你调用$ .post()时)?

  • 为什么要在第二个文件中定义自己的AJAX调用方法?您正在重新创建$ .post()。

  • 的功能
  • 如果你想做很多ajax编程,我强烈建议你学习:
    • 如何使用Fiddler
    • HTTP协议(以便您可以了解Fiddler向您展示的内容)。