簡體   English   中英

數據未通過Ajax傳遞到PHP腳本

[英]Data not getting passed via Ajax to PHP script

我正在嘗試通過ajax將變量編號的值發送到PHP腳本。 但是,PHP腳本無法在瀏覽器上打開時輸出所需的輸出。 嘗試過,但在這里找不到問題。 有指針嗎?

index.html

<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>

<script>

var number = 0;

function process()
{
    number++;

    var xhr;

    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var data = "num=" + number;
    xhr.open("POST", "index.php", true);
    xhr.send(data);
}     
</script>

index.php

<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>

編輯我long腳的la腳答案,因為您固定了大括號...但是bloodyKnuckles是對的,您還需要在“ process”函數中添加一些內容,以從PHP頁面獲取響應並輸出響應...或者您想要執行的任何操作。 您基本上可以在XMLHttpRequest對象中使用方法“ onreadystatechange”,然后查找“ readyState”屬性值為4,這意味着一切已完成。 這是一個簡單的示例,僅將結果輸出到控制台(您可以在選擇的瀏覽器中使用開發人員工具進行查看)。

<script>

var number = 0;

function process()
{
number++;

var xhr;

 if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

var data = "num=" + number;
xhr.onreadystatechange = function(){            

  if (xhr.readyState==4 && xhr.status==200){
          console.log('xhr.readyState=',xhr.readyState);
          console.log('xhr.status=',xhr.status);
          console.log('response=',xhr.responseText);               
  }

  else if (xhr.readyState == 1 ){
    xhr.send(data)

  }

};

xhr.open("POST", "ajax-test.php", true);

}
</script>

當您走得更遠時,您可能希望更新PHP頁面以僅在POST值存在時更新會話。

<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
            session_start();
    $_SESSION['numb'] = $_POST['num'];
    echo $_SESSION['numb'];
}
?>

您可以取消注釋那些ini_set和error_reporting行,以嘗試弄清楚PHP腳本正在發生什么。

這是因為您沒有通過請求發送標頭信息...

追加此代碼

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");

xhr.open("POST", "index.php", true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM