AJAX数据没有传递给PHP

时间:2017-06-13 08:33:34

标签: javascript php jquery mysql ajax

我无法将AJAX数据传递给PHP。我对PHP很有经验,但对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);

我知道一般的AJAX提取和PHP代码正在工作,因为我可以手动创建$ commodity_code变量,脚本工作正常。我认为我的问题在于将AJAX数据传递给我的PHP脚本。

2 个答案:

答案 0 :(得分:6)

您忘了在AJAX通话中添加method: 'POST'。你的电话有问题。检查以下内容:

$.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);
  }  
});

或者为了简单起见,请使用速记功能:

$.post('get_code.php', {commodity_code: commodity_code}, function(data) {
  var commodity_desc = data[0];
  alert(commodity_desc);
});

答案 1 :(得分:0)

此行data: "commodity_code: commodity_code",中的

错误..您可以简单地传递commodity_code变量..

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