duanchuli5647 2013-09-24 15:41
浏览 34
已采纳

无法通过AJAX获取PHP变量

I am using Wordpress and I have a page where I have a drop down that when the links are clicked it will make an Ajax call and pass the data variable to PHP, at least that is what I'm attempting to do lol.

When clicking on the link I check my browser and in the Network tab for the page I receive a variable for the data object in the html and the ajax post's to the php page but for some reason I can't get a value.

My HTML

<div class="category-submenu">
    <ul>
        <li><a href="#" data-office="Corporate">Corporate</a></li>
        <li><a href="#" data-office="Office1">Office1</a></li>
        <li><a href="#" data-office="Office2">Office2</a></li>
        <li><a href="#" data-office="Office3">Office3</a></li>
    </ul>
</div>

My jQuery

$('.category-submenu a').click(function(){
    $.ajax({
        type: "POST",
        url: "/load-team.php",
        dataType: 'json',
        data: {office: $(this).data('office')},
        success: function(data) {
            $.each( data, function(i, item) {
                alert(data[i].start);
            });
        }
    });
});

My PHP

<?php

    $office = $_GET['office'];
    $link = mysql_pconnect("localhost", "root", "root") or die("Could not connect");

    mysql_select_db("somedb") or die("Could not select database");

    $arr = array();
    $query = mysql_query("SELECT first_name, last_name FROM ic_team_members WHERE office ='" . $office . "'");

    while($obj = mysql_fetch_object($query)) {
        $arr[] = $obj;
    }

    echo '{"members":'.json_encode($arr).'}';

 ?>

I'm sure there is some code missing or my syntax might be incorrect in some parts but I can't seem to find where, if any place.

Again I want to grab the data object from HTML element, pass it through Ajax into PHP and return the result as json object, which I can do but for some reason I think the error is in my PHP.

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • donglan7594 2013-09-24 15:42
    关注

    You are passing it by POST, and therefore you need to receive it with POST:

    $office = $_POST['office'];
    

    Otherwise, use GET to send the ajax request:

    $.ajax({
        type: "GET",
        ...
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器