XMLHttpRequest响应状态基于发布值

时间:2014-09-25 05:55:45

标签: javascript php ajax xmlhttprequest

我有我的JavaScript函数,它执行XMLHttpRequest。这是我的代码。

function addbilldetails() {

    // Cancel the form submit
    event.preventDefault();

    // The URL to POST our data to
    var postUrl = 'http://example.com/post.php';

    // Set up an asynchronous AJAX POST request
    var xhr = new XMLHttpRequest();
    xhr.open('POST', postUrl, true);

    // Prepare the data to be POSTed
    var clientId = "clientid",
    submittype = "a",
    name = encodeURIComponent(document.getElementById('name').value),
    billno = encodeURIComponent(document.getElementById('billno').value),
    mobileno = encodeURIComponent(document.getElementById('mobileno').value),
    phoneno = encodeURIComponent(document.getElementById('phoneno').value),
    netAmount = encodeURIComponent(document.getElementById('netAmount').value);

    var params = 'clientId=' + clientId +
                 '&billno=' + billno + 
                 '&mobileno=' + mobileno + 
                 '&phoneno=' + phoneno +
                 '&netAmount=' + netAmount +
                 '&type=' + submittype +
                 '&name=' + name;

    // Replace any instances of the URLEncoded space char with +
    params = params.replace(/%20/g, '+');

    // Set correct header for form data 
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    // Handle request state change events
    xhr.onreadystatechange = function() { 
        // If the request completed
        if (xhr.readyState == 4) {
            statusDisplay.innerHTML = '';
            if (xhr.status == 200) {
                // If it was a success, close the popup after a short delay
                statusDisplay.innerHTML = 'Saved!';
               document.getElementById('save').disabled = false;
                // window.setTimeout(window.close, 1000);
            } else {
                // Show what went wrong
                statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
            }
        }
    };

    // Send the request and set status
    xhr.send(params);
    statusDisplay.innerHTML = 'Saving...';
   document.getElementById('save').disabled = true;
}

现在,上面的代码完美无缺,并在200上返回POST。但我希望它根据发布的值在UI上返回自定义消息。

如果值POST ed小于数据库中的值,我希望它给出“输入有效数字”或类似的内容。

我对XMLHttpRequest很安静。我不知道如何实现这一目标。任何帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

而不是statusDisplay.innerHTML = 'Saved!';您考虑过:

statusDisplay.innerHTML = xhr.responseText;

如果您这样做,那么您的statusDisplay将等于post.php回声中的任何内容。

例如,在post.php中

<?php

//handling $_POST['clientId'] ... etc

if (error)
    echo "Enter Valid Number";
else
    echo "Saved!";