douciping4283 2010-08-27 15:32
浏览 34
已采纳

在jQuery中正确使用$ .post

I have a website built across a series of pages and scripts, and I'm trying to link them together using Ajax. I was told the easiest way to send back to the server was using jQuery, so I'm trying that out but I can't seem to get it to work. My three files are as follows, with the methods in question being the lines containing onclick() and the MySQL query in file 3.

Here's the page itself:

<!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>

Here's the .js script containing my the series of functions called first by 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;
    }

And finally, the script that should be receiving the POST data:

<?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."'"
           );

?>

Where am I going wrong? Are the variables from the Javascript file (which is included in the page) not available to onclick? Everything works as it should except for the MySQL update in the third file.

  • 写回答

1条回答 默认 最新

  • duandanai6470 2010-08-27 15:39
    关注

    A handful of things:

    • Where is the variable "victim" being defined (in your first file, when you make the call to $.post() )?

    • Why are you defining your own method of making an AJAX call in the second file? You're recreating the functionality of $.post().

    • If you want to do a lot of ajax programming, I highly encourage that you learn:
      • How to use Fiddler
      • The HTTP protocol (so that you can understand what Fiddler is showing you).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程