codeigniter - How can we check data in controller sent by ajax (not in response) in codeigniter?
问题描述
I want to send array data from javascript to a view page..But the array isn't getting passed to the view page. The codes are described below:
//array getting passed from this page
<input type="button" name="b">
<script src="<?php echo base_url().'assets/js/' ?>jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[type='button']").click(function(){
question_array=[];
question_array['what is our nationality?']='Bangladeshi';
question_array['what is our national fish?']='Ilish';
number=10;
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "admin/test",
dataType: 'json',
data: {question_array: question_array,number:number},
success: function(result) {
if (result) {
window.location="<?php echo base_url().'admin/test_page'; ?>";
}
}
});
});
});
</script>
`
In my controller::
public function test()
{
$question_array = $this->input->post('question_array');
$number = $this->input->post('number');
$this->session->set_flashdata('number', $number);
$this->session->set_flashdata('question_array', $question_array);
echo json_encode($number, $question_array);
}
function test_page()
{
$this->load->view('admin/test_page');
}
//The page where I'm sending the array(Question_array not found)
$number = $this->session->flashdata('number');
$question_array = $this->session->flashdata('question_array');
echo $number;
print_r($question_array);
解决方案
我希望下面的代码可以帮助你。您需要使用 stringify 发布字符串 i 更正 JSON 格式。服务器将接收 json 并将其解码为对象。
function send(){
var url = "http://localhost/some_url_here";
var data = JSON.stringify({
Bangladeshi: 'what is our nationality?',
Ilish: 'what is our national fish?'
});
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
}).done(function(output){
alert('output is '+ JSON.stringify(output));
});
}
function receive()
{
$result = '';
$stream_clean = $this->security->xss_clean($this->input->raw_input_stream);
$request = json_decode($stream_clean);
$Bangladeshi = $request->Bangladeshi;
$Ilish = $request->Ilish;
$result = array("status" => 200, "id" => $Bangladeshi+$Ilish);
header('Content-Type: application/json');
echo json_encode($result);
}
推荐阅读
- python - Circuitpython 和日文脚本
- verilog - binary to bcd verilog output is always x
- java - Is there any way to dynamically compile java code at runtime
- c# - System.Text.Json.JsonException error message triggered when app is running
- .net - .NET How to check if a list
is in numerical order (1-9)? - iframe - Is this possible to only load an iframe after user begins scrolling?
- matlab - Localize and Read BarCodes with Matlab Code
- react-native - How clamp function works within a screen boundary?
- python - Syntax error on else: statement in code + idk why it keeps saying I have a bad title
- javascript - How to request refresh and access tokens from Spotify API?