2

我正在尝试设置一个变量 $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);
4

4 回答 4

3

$_GET为此,在 URL 中传递了一个参数;

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

该参数$_GET['q']将等于'search'

因此,当您执行 AJAX 请求时,您需要在 URL 中指定参数。

编辑

试着摆脱你的HTTP_X_REQUESTED_WITH陈述。如果没有这些检查,请求可能足够安全。只需将其简化为:

if ( isset( $_GET["categoryID"] ) ) {
  $id = $_GET["categoryID"];
}
于 2012-05-10T17:17:36.083 回答
1

不需要:

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:我刚刚注意到另一个问题:categoryIDajax 中的数据部分没有被添加:

  • 您正在请求/发布到 (???) :(select-menu.php注意,没有查询字符串!)
  • 您发送的数据是:{ ajax: true, anotherval: "anotherAction" }{ ajax: true}

因此,categoryID永远不会出现在select-menu.php.

最合乎逻辑的做法是将所选类别添加到数据部分:

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

和:

data: { "ajax": true, "categoryID": cat } 
于 2012-05-10T17:31:16.560 回答
0

使用 jQuery,您可以使用jQuery.get()或添加type='GET'参数到jQuery.ajax(). 一些例子:

jQuery(function($) {
    $.ajax({
        url : 'your-page.php',
        type : 'GET', 
        data : {
            'paramName' => 'paramValue',
            'foo' => 'bar'
        },
        success : function(data) {
             // do something in the callback function
        }
    });
});
于 2012-05-10T17:24:41.050 回答
0

您需要传递以下值jQuery.get()

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

在您的 php 中,只需回显您的 cateogryId 以查看它是否正常工作

<?php echo $_GET['categorID'] ?>
于 2012-05-10T17:25:42.177 回答