簡體   English   中英

PHP $ _GET與Ajax / Jquery請求

[英]PHP $_GET with Ajax/Jquery Request

我正在嘗試設置變量$ id = $ _ GET [“ categoryID”]。 我無法正常工作。 我相信這與Ajax請求有關。 但是我不知道該如何格式化它才能使其與該請求結合使用。 我需要用於mysql查詢的變量。 任何幫助是極大的贊賞。 這是我的頭,已經為此奮斗了幾天。 我已經嘗試了GET和POST。 謝謝。

我已經將頁面精簡到了...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>
</head>
<body>
<?php 
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

        $id = $_GET["categoryID"];
        //$id=3; 
        }
?>
  print_r($_GET) = <?php print_r($_GET); ?>
  <br />
  print_r($id) = <?php print_r($id); ?> 
</body>
</html> 

這是結果頁面。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test $_GET</title>
    </head>
    <body>
          print_r($_GET) = Array
(
    [categoryID] => 1001
)
      <br />
      print_r($id) =  
    </body>
    </html> 

這是整個頁面。

<?php
if (@$_REQUEST['ajax']) {
    $link = $nm33;
    if ($link == false)
        trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
    $connected = mysql_select_db('nm', $link);
    if ($connected) {

    //How do I set $id = $_GET["categoryID"] It fails to set the variable.

        $id =$_GET["categoryID"];
    //  $id=1;
    // It will work as $id=1    

        $results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');

    //////////  


        $json = array();
        while (is_resource($results) && $row = mysql_fetch_object($results)) {
            //$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
            $json[] = '"' . $row->label . '"';
        }
        echo '[' . implode(',', $json) . ']';
        die(); // filthy exit, but does fine for our example.
    } else {
        user_error("Failed to select the database");
    }
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/select-chain.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    <!--
    $(function () {
        var cat = $('#categorySelect');
        var el = $('#elementSelect');
        var attr = $('#attributeSelect');

        el.selectChain({
            target: attr,
            url: 'select-menu.php',
            data: { ajax: true, anotherval: "anotherAction" }            
        });        

        // note that we're assigning in reverse order
        // to allow the chaining change trigger to work
        cat.selectChain({
            target: el,
            url: 'select-menu.php',
            data: { ajax: true }
        }).trigger('change');

    });
    //-->
    </script>
<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
  <select name="category" class="dropdown" id="categorySelect">
    <option selected="selected">Select Your Vehicle</option>
    <?php do { ?>
    <option> <?php echo $row_rsMake['make']; ?></option>
    <?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
  </select>
  <select name="model" class="dropdown" id="elementSelect">
    <option selected="selected">Select Model</option>
    <option>[none selected]</option>
  </select>
  <select name="appYear" class="dropdown" id="attributeSelect" >
    <option selected="selected"> </option>
    <option>[none selected]</option>
  </select>
  <input  type="submit" value="Go">
</form>
<p><br />
  <br />
  print_r($_GET) = <?php print_r($_GET); ?> <br />
  print_r($_REQUEST) = <?php print_r($_REQUEST); ?><br />
  echo $_REQUEST['categoryID']  <?php  echo $_REQUEST['categoryID'];?>
</p>

這是select-chain.js

(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };

                var settings = $.extend({}, defaults, options);

        if (!(settings.target instanceof $)) settings.target = $(settings.target);

        return this.each(function () {
            var $$ = $(this);

            $$.change(function () {
                var data = null;
                if (typeof settings.data == 'string') {
                    data = settings.data + '&' + this.name + '=' + $$.val();
                } else if (typeof settings.data == 'object') {
                    data = settings.data;
                    data['category'] = $$.val();
                    data['model'] = $$.val();
                    data['year'] = $$.val();
                }

                settings.target.empty();

                $.ajax({
                    url: settings.url,
                    data: data,
                    type: (settings.type || 'get'),
                    dataType: 'json',
                    success: function (j) {
                        var options = [], i = 0, o = null;

                        for (i = 0; i < j.length; i++) {
                            // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                            o = document.createElement("OPTION");
                            o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
                            o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
                            settings.target.get(0).options[i] = o;
                        }

            // hand control back to browser for a moment
            setTimeout(function () {
                settings.target
                                .find('option:first')
                                .attr('selected', 'selected')
                                .parent('select')
                                .trigger('change');
            }, 0);
                    },
                    error: function (xhr, desc, er) {
                        // add whatever debug you want here.
            alert("an error occurred here");
                    }
                });
            });
        });
    };
})(jQuery);

為此,在URL中傳遞了$_GET參數。

http://www.google.com/?q=search

參數$_GET['q']等於'search'

因此,當您執行AJAX請求時,您需要在URL中指定參數。

編輯

嘗試擺脫HTTP_X_REQUESTED_WITH語句。 如果沒有這種檢查,該請求可能足夠安全。 只需將其簡化為:

if ( isset( $_GET["categoryID"] ) ) {
  $id = $_GET["categoryID"];
}

不需要:

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

您可以使用:

$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;

與(但更短...)相同:

if (isset($_GET["categoryID"]))
{
  $id =  intval($_GET["categoryID"]);
}
else
{
  $id =  0;
}

如果要檢查是否通過ajax發出了請求,則必須重寫腳本,因為不需要整個header部分。 相反,您可以從頁面調用此腳本,在頁面本身中設置一個變量,如果腳本中未設置該變量,則為ajax調用。 顯然,這只是一個簡單的例子。

編輯:插件沒有提到請求的默認類型是什么,但是很可能是POST因此您可以嘗試將type: "post"添加到selectChain的選項中。

並且為了確保您的響應是格式正確的json(當您到達那里時...),我還建議您使用json_encode ,因此:

    echo json_encode($json);
    die(); // filthy exit, but does fine for our example.

編輯2:我剛剛注意到另一個問題:沒有將categoryID添加到ajax的數據部分中:

  • 您正在請求/發布到(???): select-menu.php (注意,沒有查詢字符串!)
  • 您要發送的數據是: { ajax: true, anotherval: "anotherAction" }{ ajax: true}

因此, categoryID select-menu.php永遠不會出現在select-menu.php

最合乎邏輯的做法是將所選類別添加到數據部分:

data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat } 

和:

data: { "ajax": true, "categoryID": cat } 

使用jQuery時,您可以使用jQuery.get()或向jQuery.ajax()添加type='GET'參數。 一些例子:

jQuery(function($) {
    $.ajax({
        url : 'your-page.php',
        type : 'GET', 
        data : {
            'paramName' => 'paramValue',
            'foo' => 'bar'
        },
        success : function(data) {
             // do something in the callback function
        }
    });
});

您需要在jQuery.get()傳遞值:

$.get('yourphppage.php', { categoryID : 1234 }, function(data) { 
    alert(data);
});

在您的PHP中,只需回顯右擊您的cateogryId即可查看其是否正常運行

<?php echo $_GET['categorID'] ?>

暫無
暫無

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

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