簡體   English   中英

使用JQuery $ .GET和$ .POST

[英]Using JQuery $.GET and $.POST

您將不得不原諒我的問題。 我對使用PHP,HTML和CSS相當熟悉。 但是,我正在嘗試為一個小型項目編寫一個簡單的統計收集器。 我已經列舉了許多使用jQuery或Ajax的示例。 我決定使用jQuery作為我的第一種方法。 目的是從getinfo.php文件中導入值,將其分配給變量,然后將收集的信息發布到數據庫中以供以后分析。 但是,我遇到了一些麻煩。.我正在使用$ .GET請求來拉入此php文件。

GETINFO.PHP

<?php
$browserID = $_SERVER ['HTTP_USER_AGENT'];
$ip = $_SERVER ['REMOTE_ADDR'];
$url = $_SERVER ['REQUEST_URI'];

echo $browserID;
echo $ip;
echo $url;
?>

對於我的例子來說,很簡單,沒有什么特別的。 對於我的jQuery get和post請求,我編寫了此代碼。

 <script type="text/javascript">
        $(document).ready(function(){

            // Define variables to send
            var pageTag = "Test Text";

            // Retrieve PHP variables
            $.get("getinfo.php", function (data) {

                alert("Data:" + data)

                // Post data to database
                $.post("process.php",{
                        page: pageTag

                    },
                    function (response,status){//required callback function
                        alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);
                        //"response" receives - whatever written in echo of above PHP script.

                });
            });
        });
  </script>

如您所見,這是一團糟,是的,我是一個初學者,除了那個我。 無論如何,因此分別將這兩段代碼運行良好。 但是,當我嘗試將它們組合在一起時,卻無法獲得所需的結果。 我的var pageTag = "Test Text"; 實際發布時甚至沒有被推送到服務器。 現在我的PostgreSQL數據庫正在獲取空白條目以保存時間戳,但這是由process.php文件本身提交的。

PROCESS.PHP

 <?php
  #Creds to access the database
  require_once("connection.php");

  /* Log page and get filenames */
  #$page = input($_GET['page']) or die('ERROR: Missing page ID');
  $page = json_decode(stripslashes($_POST['page']));
  $ip_add = json_decode(stripslashes($_POST['ip_addy']));
  $browser = json_decode(stripslashes($_POST['browser']));
  $timestampInSeconds = $_SERVER['REQUEST_TIME'];
  $date = date("Y-m-d h:i:s", $timestampInSeconds);

  $sql = "INSERT INTO stats (page, date, ip, browser) VALUES ('$page','$date','$ip_add','$browser')";
  pg_query($db,$sql);

  echo $page;
  echo $ip_add;
  echo $date;

  $query="SELECT COUNT(*) total FROM stats WHERE page= '$page'";
  $result = pg_query($db,$query);
  $row = pg_fetch_array($result,0,PGSQL_NUM);
  $count = $row[0];

  $query = "SELECT count(distinct IP) FROM stats WHERE page= '$page'";
  $result = pg_query($db,$query);
  $row = pg_fetch_array($result,0,PGSQL_NUM);
  $UniaquCount = $row[0];
  pg_close($db);

  exit();

因此,快速回顧一下。 我需要使用getinfo.php從客戶端提取一些數據,然后通過jquery將這些請求發布到process.php以便傳遞到數據庫。 任何幫助是極大的贊賞!

您沒有在Process.php文件中發回任何東西。

請嘗試以下操作:

$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

准備所有數據后,請在process.php末尾使用此功能。 您不一定需要status參數。 只需以所需的任何格式制作數據即可。

有很多錯誤。

首先,在您的“ getinfo.php”中,使用json正確響應。 喜歡:

$data = array(
             "browserid"=>$browserID,
             "ip"=>$ip,
             "url"=>$url,
             );
header('Content-Type: application/json');
echo json_encode($data);

然后在jQuery Ajax中,首先將“數據類型”設置為:“ json”,然后對其進行解析。 喜歡:

$.ajax({
  type: "GET",
  dataType: "json",
  url: "getinfo.php",
  success: function(data) {
      var browserid = data["browserid"];
      var ip = data["ip"];
      var url = data["url"];
      //
      // Continue, the POST part (or) whatever you want here..
      //
  }
});

非常感謝所有在此方面為我提供幫助的人。 這是我用於ajax請求的最終代碼片段:

 <script type="text/javascript">
        $(document).ready(function(){

            // Create the AJAX request
            $.ajax({
                type: "GET",                                       // Using the POST method
                url: "getinfo.php",                                 // The file to call
                dataType: "json",                                   // Our data to pass

                success: function (data) {                               // What to do on success
                    //On success define the following variables from getinfo.php
                    var ip = JSON.stringify(data["ip"]);
                    var url = JSON.stringify(data["url"]);
                    var browser = JSON.stringify(data["browser"]);

                    $.ajax({
                        type: "POST",        //Using the POST method
                        url: "process.php",  //The php file used to submit data to database
                        dataType: "text",    // Our data to pass
                        cache: false,
                        data: {
                            page: url,
                            browser: browser,
                            ip_addy: ip,

                        },
                        success: function (response, status) {
                            alert("*----Received Data----*\n\nResponse : " + response + "\n\nStatus : " + status);

                        }
                    });

                },
            });
        });
    </script>

ajax請求提取請求的數據,然后將該數據發布到PostgeSQL數據庫。 再次感謝大家! 我希望這可以幫助其他人找出同樣的問題。

暫無
暫無

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

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