【问题标题】:Jquery 'Bad Request' error while passing array in url在 url 中传递数组时出现 Jquery 'Bad Request' 错误
【发布时间】:2014-08-26 06:52:53
【问题描述】:
我有一个包含超过 10 条记录的数组,我想将它传递给控制器,但它会弹出错误请求。
以下是我的代码:
$('#submit_fourth').click(function(){
//send information to server
$.ajax({
type: 'POST',
url: '<?php print site_url('orgnization/storeData'); ?>/'+fields
});
});
如代码所示,fields 是包含数据的数组。现在下面是萤火虫中的错误信息。
有什么帮助吗?
【问题讨论】:
标签:
jquery
ajax
json
codeigniter
【解决方案1】:
试试这个:
$('#submit_fourth').click(function(){
//send information to server
$.ajax({
type: 'POST',
data: {fields:fields},
url: '<?php print site_url('orgnization/storeData'); ?>/'
success: function(data)
{
console.log('Success');
}
});
});
在php代码中:
public function storeData()
{
....
if($this->input->post())
{
$fields = $this->input->post('fields');
}
....
}
【解决方案2】:
您发送的数据数组格式错误。请参见下面的示例
$.ajax({
type: "POST",
url: "<?php print site_url('orgnization/storeData'); ?>",
data: { name: "John", location: "Boston" }//your data will send in this format
})
【解决方案3】:
在发布数据之前使用 JSON.stringify();并在数据中给出,不要附加在 url 中。
$('#submit_fourth').click(function(){
//send information to server
$.ajax({
type: 'POST',
url: '<?php print site_url('orgnization/storeData'); ?>/',
data: JSON.stringify(fields)
});
});
【解决方案4】:
如果你想发送 GET 请求,试试这个:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo site_url('orgnization/storeData') . '?' . http_build_query($data);
和
type: 'POST'改成type: 'GET'
如果你想发送 POST:
$.post("<?php print site_url('orgnization/storeData'); ?>", <?php echo json_encode($data); ?>)
.done(function( data ) {
alert( "Data Loaded: " + data );
});