独立HTML页面通过jQuery Ajax向CodeIgniter提交数据失败
问题分析与解决方案
你的问题核心在于CodeIgniter默认的$this->input->post()方法无法直接解析JSON格式的请求体,而你的Ajax请求通过JSON.stringify()把数据转成了JSON字符串,并设置了contentType: "json",导致控制器无法正确获取提交的数据。下面提供两种解决思路:
方案一:改用表单默认编码格式发送数据(推荐)
这种方式不需要修改CI控制器,只需要调整Ajax代码,让数据以CodeIgniter能直接识别的application/x-www-form-urlencoded格式发送:
$("#footer_enquiry").click(function(e){ e.preventDefault(); var ajxUrl = "https://www.example.com/contactus/enquiry"; // 直接传递对象,不需要JSON.stringify var ajxDataObj = { 'name' : $('input[name=f_full_name]').val(), 'contact' : $('input[name=f_contact_number]').val(), 'email' : $('input[name=f_email_address]').val(), 'description' : $('[name=f_description]').val() }; $.ajax({ type: "POST", url: ajxUrl, data: ajxDataObj, // 直接传对象,jQuery会自动转成表单格式 // 去掉contentType设置,jQuery默认就是application/x-www-form-urlencoded success: function (result) { alert(result); console.log(result); return false; }, error: function (jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } alert(msg); } }); });
这样修改后,你的原有CI控制器代码不需要任何改动,就能正常通过$this->input->post()获取到数据。
方案二:在CI控制器中手动解析JSON请求体
如果你确实需要保持JSON格式的请求,可以修改CI控制器代码,手动读取请求体的原始数据并解析:
function enquiry() { // 获取原始的JSON请求体 $rawInput = file_get_contents('php://input'); // 解析成关联数组 $requestData = json_decode($rawInput, true); $name = isset($requestData['name']) ? $requestData['name'] : ''; $contact = isset($requestData['contact']) ? $requestData['contact'] : ''; $email = isset($requestData['email']) ? $requestData['email'] : ''; $description = isset($requestData['description']) ? $requestData['description'] : ''; $data=array( 'name' => $name, 'contact' => $contact, 'email' => $email, 'description' => $description ); print_r($data); }
这种方式下,你的Ajax代码可以保持原来的JSON.stringify()和contentType: "json"设置,控制器通过php://input读取原始请求数据,再用json_decode解析成数组使用。
内容的提问来源于stack exchange,提问作者dee flor
相关产品推荐
相关产品推荐

