我如何在php中使用ajax从mysql获取数据?

时间:2010-02-11 15:36:19

标签: php ajax

我使用AJAX将数据存储在MySQL数据库中,它正在运行。但是我遇到了使用AJAX检索数据的问题。

我的存储数据编码(发布评论页面):

function sendMail(form_id) {
    // Do a client-side check; if it passes, then move on; 
    // otherwise, report an error to the user

    //if (!validatePage(form_id)) return;
    if(!checkMail(document.getElementById('txtEmail').value))
    {
        document.getElementById('txtEmail').focus();
        return false;
    }
    window.scrollTo(0,0);
    divId = "results";
    var str = "";
    var elem = document.getElementById(form_id).elements;
    for (var i = 0; i < elem.length; i++) {
        if (
            (elem[i].type == "hidden") || 
            (elem[i].type == "text") || 
            (elem[i].type == "textarea")
        ) {
            // Text field
            str += elem[i].id + "=" + escape(encodeURI(trimField(elem[i].id))) + "&";
        }
        else if (elem[i].type == "checkbox") {
            // Check box
            if (elem[i].checked) {
                str += elem[i].id + "=on&";
            }
            else {
                str += elem[i].id + "=off&";
            }
        }
        else if (elem[i].type == "select-one") {
            // Drop-down menu (SELECT)
            var sel = elem[i];
            str += sel.id + "=" + sel.options[sel.selectedIndex].value + "&";
        }
    }
    str = str.substring(0, str.length-1);
    str = str.replace(/%250A/g,"\n") // Make sure that line breaks get transmitted properly
    if (form_id == "contact_form") {
        form_page = "sendMail.php";
    }
    AjaxRequest(form_page, str, "post");
}

// Make the AJAX request
function AjaxRequest(url, parameters, type) {
    http_request = false;
    if (window.XMLHttpRequest) {
        // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
        }
    }
    else if (window.ActiveXObject) {
        // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    if (!http_request) {
        alert("Cannot create XMLHTTP instance");
        return false;
    }
    if (type == "post") {
        // POST
        http_request.open('POST', url, true);
        http_request.onreadystatechange = AjaxRequestCb;
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    }
    else if (type == "get") {
        // GET
        http_request.open('GET', url + parameters, true);
        http_request.onreadystatechange = AjaxRequestCb;
        http_request.send(null);
    }
    // if...else
}

// AJAX Callback
function AjaxRequestCb() {
    if (
        http_request.readyState == 1 || 
        http_request.readyState == 2 || 
        http_request.readyState == 3
    ) {
    }
    else if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            result = http_request.responseText;
            document.getElementById(divId).innerHTML = result;
            // If CAPTCHA failed, then repopulate it
            if (result.indexOf("CAPTCHA") > -1) {
                Recaptcha.reload();
            }
            else {
                // Clear form after email has been sent
                document.forms["contact_form"].reset(); // Not robust, I know (will modify later)
                Recaptcha.reload(); // Display a new CAPTCHA
            }
        }
        else {
            alert("Callback failed. There was a problem with the request.");
        }
    }
}

// Remove any unneccessary whitespace
function trimField(field) {
    re = /(^\s*)([^\b]*\S)(\s*$)/;
    if (re.test(document.getElementById(field).value)) {
        document.getElementById(field).value = document.getElementById(field).value.replace (re, "$2");
        return document.getElementById(field).value;
    }
    else {
        document.getElementById(field).value = "";
        return "";
    }
}

// The phone field shows how the user should input a phone number; 
// on the first focus, the value will be cleared so the user can 
// enter a phone number
function clearField(field_id) {
    if (first_time) {
        document.getElementById(field_id).value = "";
        first_time = false;
    }
}

2 个答案:

答案 0 :(得分:2)

  1. 您的AJAX将使用一些GET或POST参数查询PHP页面(这些参数可能类似于搜索过滤器或其他任何对您的项目有吸引力的参数)。您并不总是需要参数,但在大多数项目中通常需要一些参数。
  2. 此PHP页面将根据这些参数查询MySQL数据库。
  3. 最后,这个PHP页面将以XML,JSON之类的可解析格式输出数据......或者您也可以直接输出HTML,但它的可移植性较差。
  4. 然后JavaScript解释AJAX响应(PHP根据从MySQL接收的数据输出的数据)。
  5. 您可以在TizagGoogle it ...

    上查看教程

答案 1 :(得分:0)

Ajax只是意味着“在不离开当前页面的情况下发出HTTP请求”。它只关注网络服务器和浏览器之间的通信。您仍然可以获得正常的HTTP请求(在这种情况下,可能会导致PHP程序运行)。

使用PHP连接到数据库并从中获取数据的问题对于Ajax请求与任何其他请求相同。

唯一的区别是您可能希望输出除完整HTML文档之外的其他内容。