首页 > 解决方案 > 将数据发布到 Json 时返回“未定义”错误

问题描述

我想在传递参数 1 时测试我的 ajax 'PUT' 函数,但它返回未定义?

orders.json 

[ {“id”:1,“name”:“will_1”,“drink”:“cola_2”},{“id”:2,“name”:“Laura”,“drink”:“香草”
}]

$(document).ready(function(){
  $("#purchaseId").change(function() { 

        $.ajax({
          type:'POST',
          url:'orders.json',
          data: "1",
          success:function(newOrder) {
            
              alert(newOrder.name);
            
          },
      
          error:function(){
            alert("loading error");
        }       
        
      });

  });

});
<html lang="en">
<head>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>       
     <script src="home.js">
     </script>
     
    <title>Javascript on Steroids</title>
</head>
<body> 

   
        <select id = "purchaseId"  >
            <option value="1" selected >1</option>
            <option value="2">2</option>
        </select>
    
</body>
</html>

标签: json

解决方案


当你 POST 或 PUT 时,你发送data: "1",的只是参数,而不是它的值。在 GET 中它看起来像://someurl/?1=

尝试:data: "order=1",这将 POST/PUT 一个参数:order带有值:1

这种方式在后端你可以期待$_POST['order'], 并将获取它的发送值1


推荐阅读