Правильное использование $ .post в jQuery - PullRequest
0 голосов
/ 27 августа 2010

У меня есть веб-сайт, построенный на серии страниц и скриптов, и я пытаюсь связать их вместе с помощью Ajax.Мне сказали, что самый простой способ отправить обратно на сервер - это использовать jQuery, поэтому я пробую это, но не могу заставить его работать.Мои три файла выглядят следующим образом. Методами, о которых идет речь, являются строки, содержащие onclick() и запрос MySQL в файле 3.

Вот сама страница:

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

?>

Куда я иду не так?Переменные из файла Javascript (который включен в страницу) недоступны для onclick?Все работает как надо, кроме MySQL update в третьем файле.

1 Ответ

0 голосов
/ 27 августа 2010

Горстка вещей:

  • Где определяется переменная "жертва" (в вашем первом файле, когда вы вызываете $ .post ())?

  • Почему вы определяете свой собственный метод вызова AJAX во втором файле?Вы воссоздаете функциональность $ .post ().

  • Если вы хотите много заниматься ajax-программированием, я настоятельно рекомендую вам изучить:
    • Как использовать Fiddler
    • Протокол HTTP (чтобы вы могли понять, что Fiddler показывает вам).
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...