使用javascript从php文件发送和接收信息时遇到问题

时间:2016-11-06 21:03:41

标签: javascript php

我正在向运行查询的php文件发送一些信息,但我想同时从该php文件中检索一些信息。 php文件执行正常但我无法获取json_encoded对象。

将字符串和数字发送到php文件的Javascript函数:

function open_close(){
    var status = encodeURIComponent(SelectedTicket["Status"]);
    var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
    var info = "Status="+status+"&TicketNum="+ticketNum;
    var http3 = createAjaxRequestObject();

    if (http3.readyState == 4) {
        if (http3.status == 200){
            alert("Ticket Updated!");  //This never gets hit                     
            getUpdatedTicket(JSON.parse(http3.responseText));
        }
    }

    http3.open("POST", "openClose.php", true);
    http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http3.send(info);
}

获取字符串和数字并更新表的PHP文件

<?php
    include("config.php");
    session_start();

    $status = $_POST["Status"];
    $num = $_POST["TicketNum"];
    $newStatus = " ";
    if(strcmp($status, "Open") == 0){
        $newStatus = "Closed";
    }
    elseif(strcmp($status, "Closed") == 0){
            $newStatus = "Open";
    }

    $sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
    $r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");

    $sql = "SELECT * FROM tickets where TicketNum = $num";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }

    echo json_encode($data);

?>

如何在同一个javascript函数中检索json_encoded对象?

1 个答案:

答案 0 :(得分:1)

您需要readyState监听器才能知道请求何时完成,然后从responseText

获取数据
function open_close() {
    var status = encodeURIComponent(SelectedTicket["Status"]);
    var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
    var info = "Status=" + status + "&TicketNum=" + ticketNum;
    var http3 = createAjaxRequestObject();

    http3.onreadystatechange = function () {
        if (http3.readyState == 4) {
            if (http3.status == 200) {
                console.log(http3.responseText); // <- it's there
            }
        }    
    }

    http3.open("POST", "openClose.php", true);
    http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http3.send(info);
}