使用POST通过AJAX发送的PHP文件没有变量

时间:2014-11-14 11:13:03

标签: javascript php jquery ajax

我尝试将jquery变量发送到php脚本,作为我为网站构建的搜索功能的一部分。我希望使用AJAX来执行php文件的请求,到目前为止,我已将此作为new-search.js脚本:

$('#bt_search').click(function(){
        $keyword = $('#keyword').val();//get the keyword from the input box
        $contentArray = []; //Hold checked "content" filters
        $typeArray = []; //Hold checked "type" filters
        $locationArray = []; //Hold checked "location" filters

        //Content Filter - cycle through each filter and add value of checked ones to array
        $('.content-filter :checked').each(function(){
            $contentArray.push(this.value);
        })

        //Type Filter
        $('.type-filter :checked').each(function(){
            $typeArray.push(this.value);
        })

        //Location Filter
        $('.location-filter :checked').each(function(){
            $locationArray.push(this.value);
        })

        //Testing 
        console.log("Keyword: " + $keyword);
        console.log("Content Filters: " + $contentArray);
        console.log("Type Filters: " + $typeArray);
        console.log("Location Filters: " + $locationArray);


        /*
         * Make AJAX Request to "new-search-get-results.php", passing 
         * keyword and filter arrays to the requested file.
         * 
         */ 
        $.ajax({
            url: "../pages/ajax/new-search-get-results.php",
            data: JSON.stringify({keyword: $keyword}),
            type: "POST",
            success: function(response){
                console.log(response);
            }
        });

以上情况正在发挥作用,但是我从new-search-get-results.php文件返回的响应遇到了麻烦。这是错误:

( ! ) Notice: Undefined index: keyword in C:\wamp\www\mysite.tld\pages\ajax\new-search-get-results.php on line 6

php文件中涉及的行是:$keyword = $_POST['keyword'];

有谁知道我哪里出错了所以我可以修复这个错误?这是我的new-search-get-results.php文件:

$keyword = $_POST['keyword'];
echo $keyword;

1 个答案:

答案 0 :(得分:5)

变化

data: JSON.stringify({keyword: $keyword}),

data: {keyword: $keyword},