简体   繁体   English

PHP $ _GET与Ajax / Jquery请求

[英]PHP $_GET with Ajax/Jquery Request

I am trying to set a variable $id=$_GET["categoryID"]. 我正在尝试设置变量$ id = $ _ GET [“ categoryID”]。 I cannot get it to work. 我无法正常工作。 I believe it has to do with the the Ajax request. 我相信这与Ajax请求有关。 But I don't know how I have to format it so that it will work in conjunction with that request. 但是我不知道该如何格式化它才能使其与该请求结合使用。 I need the variable for a mysql query. 我需要用于mysql查询的变量。 Any help is greatly appreciated. 任何帮助是极大的赞赏。 This is over my head and have been struggling with it for days. 这是我的头,已经为此奋斗了几天。 I have tried both GET and POST. 我已经尝试了GET和POST。 Thanks. 谢谢。

I have distilled the page down to this... 我已经将页面精简到了...

<!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> 

Here is the resulting page.... 这是结果页面。

<!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> 

Here is the whole page.... 这是整个页面。

<?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>

Here is select-chain.js 这是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);

A $_GET parameter is passed in the URL so for this; 为此,在URL中传递了$_GET参数。

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

The parameter $_GET['q'] would be equal to 'search' 参数$_GET['q']等于'search'

So when you perform your AJAX request you need to specify the parameters in the URL. 因此,当您执行AJAX请求时,您需要在URL中指定参数。

EDIT : 编辑

Try getting rid of your HTTP_X_REQUESTED_WITH statements. 尝试摆脱HTTP_X_REQUESTED_WITH语句。 The request is probably safe enough without those kind of checks. 如果没有这种检查,该请求可能足够安全。 Just simplify it to: 只需将其简化为:

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

There is no need for: 不需要:

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

You can just use: 您可以使用:

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

Which is the same as (but shorter...): 与(但更短...)相同:

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

If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. 如果要检查是否通过ajax发出了请求,则必须重写脚本,因为不需要整个header部分。 Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. 相反,您可以从页面调用此脚本,在页面本身中设置一个变量,如果脚本中未设置该变量,则为ajax调用。 Obviously this is just a simple example. 显然,这只是一个简单的例子。

Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain . 编辑:插件没有提到请求的默认类型是什么,但是很可能是POST因此您可以尝试将type: "post"添加到selectChain的选项中。

And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode , so: 并且为了确保您的响应是格式正确的json(当您到达那里时...),我还建议您使用json_encode ,因此:

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

Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax: 编辑2:我刚刚注意到另一个问题:没有将categoryID添加到ajax的数据部分中:

  • You are requesting / posting to (???) : select-menu.php (notice, no query string!) 您正在请求/发布到(???): select-menu.php (注意,没有查询字符串!)
  • The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true} 您要发送的数据是: { ajax: true, anotherval: "anotherAction" }{ ajax: true}

So there is no way that categoryID is ever going to show up in select-menu.php . 因此, categoryID select-menu.php永远不会出现在select-menu.php

The most logical thing to do, would be to add the selected category to the data section: 最合乎逻辑的做法是将所选类别添加到数据部分:

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

and: 和:

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

With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax() . 使用jQuery时,您可以使用jQuery.get()或向jQuery.ajax()添加type='GET'参数。 Some example: 一些例子:

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

You need to pass the value in the jQuery.get() : 您需要在jQuery.get()传递值:

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

In your php just echo right back your cateogryId to see if it is working 在您的PHP中,只需回显右击您的cateogryId即可查看其是否正常运行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM