Rest Api PUT方法没有接收值

时间:2016-01-03 18:08:25

标签: jquery codeigniter rest put

我在Ajax / Jquery中有这个代码,我试图向我的API请求PUT方法。在我的代码中,我试图发送已在我的文本字段中更新的数据。 API应该接收这些数据并将其发送到模型,它应该用于根据收到的ID更新数据库中的记录。出于某种原因,我的控制器中的REST API没有从我的文本字段中接收值。

我发送数据的代码:

$("#edit").on("click", function() {
     var updatedData ={ question: $('#questionField').val(),
                        image: $('#imageField').val(),
                        answer1: $('#answer1Field').val(),
                        answer2: $('#answer2Field').val(),
                        answer3: $('#answer3Field').val(),
                        answer4: $('#answer4Field').val(),
                         };
      $.ajax({
              url : '../admincontroller/getdatabasedata/', 
              type: 'PUT',
              dataType: 'json', 
              data: updatedData,

              success: function(updatedQuestion)
              {
                JSON.stringify(updatedQuestion);
                if(updatedQuestion.ok == 1) {
                  alert("Succesfully edited");
                }
                else{
                  alert(updatedQuestion.ok);
                }
              }
          });
    return false; 
  });

应该接收数据的REST API代码:

    else if ($this->input->server('REQUEST_METHOD') == 'PUT' )
            {
                    $id = $this->input->post('idField');
                    $question = $this->input->post('questionField');
                    $image = $this->input->post('imageField');
                    $answer1 = $this->input->post('answer1Field');
                    $answer2 = $this->input->post('answer2Field');
                    $answer3 = $this->input->post('answer3Field');
                    $answer4 = $this->input->post('answer4Field');

if($question != '' && $image != '' && $answer1 != '' && $answer2 != '' && $answer3 != '' && $answer4 != ''){
                        $this->adminmodel->updateQuestion($id,$question,$image,$answer1,$answer2,$answer3,$answer4);
                        echo json_encode(array('ok' => 1));
                    }
                    else{
                        echo json_encode(array('ok' => $question));
                    }   

            }

目前我正在尝试提醒以查看数据是否已通过,但我只是获得了NULL。知道为什么吗?感谢。

2 个答案:

答案 0 :(得分:0)

我认为数据需要是一个字符串。对象被转换为查询字符串,这是你在这里看到的。

data:JSON.stringify(updatedData)而不是updatedData

答案 1 :(得分:0)

遵循类似的数据合约结构和参数名称。如果您使用原始类型在url中传递它们或在api函数中标记在body中发送的基本类型。 使用JSON.stringify(object)作为Ajax调用发送对象的数据。 确保在服务器上启用http谓词。