麻烦将jQuery ajax转换为纯JavaScript

时间:2014-04-09 23:46:46

标签: javascript php jquery ajax json

我正在努力将jQuery ajax请求转换为纯JavaScript,因此我知道如何以两种方式执行此操作。我想要做的是将我的PHP脚本中的JSON对象传递到我的JavaScript文件中,并在页面上显示JSON对象的值。

我刚刚开始深入研究AJAX,并且我已经让jQuery版本足够轻松地完成了自己的工作,但我在使用纯JavaScript版本方面遇到了困难。对于纯JavaScript部分,我跟随着我的JavaScript书籍。这就是代码结构可能看起来不同的原因。

另外,我知道没有真正的安全实现,这很好。这只是为了我自己的学习目的。

这是HTML:

<body>
    <h3>Grab the location of a person in the database below</h3>
    <form action="ajax/name.php" method="POST" name="ajaxForm" id="ajaxForm">
        <label for="name">Name: </label>
        <input type="text" id="name" name="name">
        <input type="submit" id="name-submit" name="name-submit" value="Grab">
    </form>

    <div id="results">
        <label for="location">Location: </label>
        <input type="text" name="name-data" id="name-data" disabled>
    </div>

    <div id="insert">
        <h3>Insert a new person with a new location below</h3>
        <form action="ajax/name.php" method="POST" name="insForm" id="insForm">
            <label for="name">Name: </label>
                <input type="text" name="ins-name" id="ins-name">
            <label for="location">Location: </label>
                <input type="text" name="ins-location" id="ins-location">
                <input type="submit" id="ins-submit" name="ins-submit" value="Insert">
        </form>
        <div id="insresults_name"></div>
        <div id="insresults_loc"></div>
    </div>

    <script src="js/ajax.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="js/global.js"></script>
</body>

这是我的jQuery代码可以正常工作:

$('document').ready(function() {
var locForm = $('#ajaxForm');
var insForm = $('#insForm');

locForm.submit(function() {
    $.ajax({
        type: 'POST',
        url: locForm.attr('action'),
        data: locForm.serialize(),
        success: function (response) {
            $('#name-data').val(response);
        }
    });

    return false;
});

insForm.submit(function() {
    $.ajax({
        type: 'POST',
        url: insForm.attr('action'),
        data: insForm.serialize(),
        dataType: 'json',
        success: function (response) {
            $('#insresults_name').text('Name: ' + response[0]);
            $('#insresults_loc').text('Location: ' + response[1]);
        }
    });

    return false;
});
});

这是我的PHP脚本:

<?php

if (isset($_POST['name'])) {
    require '../db/connect.php';
    $conn = new Con();
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
    $stmt->bindParam(':name', $name);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    echo (isset($result['location'])) ? $result['location'] : 'That name isn\'t listed';
}

if (isset($_POST['ins-name']) && isset($_POST['ins-location'])) {
    require '../db/connect.php';
    $conn = new Con();
    $name = filter_input(INPUT_POST, 'ins-name', FILTER_SANITIZE_STRING);
    $loc = filter_input(INPUT_POST, 'ins-location', FILTER_SANITIZE_STRING);

    $stmt = $conn->prepare('INSERT INTO names (name, location) VALUES (:name, :loc)');
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':loc', $loc);

    try {
        $stmt->execute();
        $result = $stmt->rowCount();
        if ($result) {
            $stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
            $stmt->bindParam(':name', $name);
            $stmt->execute();

            $res = $stmt->fetch(PDO::FETCH_ASSOC);
            $val = array();
            $val[0] = $res['name'];
            $val[1] = $res['location'];

            echo json_encode($val);
        } else {
            echo 'Fail';
        }
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage() . '';
    }

}

?>

这是我提出的简单的JavaScript,但不起作用:

function getData() {
    'use strict';
    var name = document.getElementById('ins-name').value();
    var location = document.getElementById('ins-location').value();
    var url = document.getElementById('ins-name').getAttribute('action');
    if ((name.length > 0) && (location.length > 0)) {
        var ajax = getXMLHttpRequestObject();
        ajax.ononreadystatechange = function () {
            if (ajax.readyState == 4) {
                // Check the status code:
                if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
                    // if ajax.responseText isn't empty
                    if (ajax.responseText) {
                        var arr = Array();
                        arr = JSON.parse(responseText);
                        document.getElementById('insresults_name').innerHTML('Name: ' + arr[0]);
                        document.getElementById('insresults_loc').innerHTML('Location: ' + arr[1]);
                    } else {
                        alert('Something went wrong!');
                    }
                } else {
                    alert('Bad Status Code!');
                }
            }
        };
        ajax.open('POST', '../ajax/name.php', true);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data = 'name=' + encodeURIComponent(name) + 'location=' + encodeURIComponent(location);
        ajax.send(data);
        return false;
    } else {
        alert('Please complete the form!');
    }
}

function init() {
    'use strict';
    if (document && document.getElementById) {
        var form = document.getElementById('insForm');
        form.onsubmit = getData;
    }
}
window.onload(init);

0 个答案:

没有答案