douou1872 2017-06-13 08:33
浏览 12
已采纳

AJAX数据没有传递给PHP

I am having trouble passing AJAX data to PHP. I am experienced with PHP but new to JavaScript.

HTML / JavaScript

<input type="text" id="commodity_code"><button id="button"> = </button>

<script id="source" language="javascript" type="text/javascript">

$('#button').click(function()
{
  var commodity_code = $('#commodity_code').val();

  $.ajax({                                      
  url: 'get_code.php',  
  data: "commodity_code: commodity_code",
  dataType: 'json',
  success:function(data) {
        var commodity_desc = data[0];
        alert(commodity_desc);
    }  
  });
}); 

</script>

PHP

$commodity_code = $_POST['commodity_code'];

$result = mysql_query("SELECT description FROM oc_commodity_codes WHERE code = '$commodity_code'");
$array = mysql_fetch_row($result);
echo json_encode($array);

I know the general AJAX fetch and PHP code is working as I can manually create the $commodity_code variable and the script works fine. I think my issue lies somewhere in passing the AJAX data to my PHP script.

  • 写回答

2条回答 默认 最新

  • doumou3883 2017-06-13 08:34
    关注

    You forgot to add the method: 'POST' in your AJAX Call. And you have some issues with your call. Check below:

    $.ajax({                                      
      url: 'get_code.php',
      method: "POST",                         // Change here.
      data: {commodity_code: commodity_code}, // Change here.
      dataType: 'json',                       
      success:function(data) {
            var commodity_desc = data[0];
            alert(commodity_desc);
      }  
    });
    

    Or to make it simple, use the shorthand function:

    $.post('get_code.php', {commodity_code: commodity_code}, function(data) {
      var commodity_desc = data[0];
      alert(commodity_desc);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失