这里是我的 Blade 的代码,它可以工作并发送请求,但我无法从 AJAX 检索数据。
Javascript
function addUser() {
var name=document.getElementById("name").value;
var email=document.getElementById("email").value;
var password=document.getElementById("password").value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type:'POST',
url:'addUser',
data: {name:name,email:email,password:password,},
success:function(data) {
$("#msg").html(data.msg);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
contentType: false,
processData: false,
});
}
Controller
public function index(Request $request) {
$msg=User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt( $request->password),
]);
return response()->json(array('msg'=> $msg), 200);
}
最佳答案
删除
contentType: false,
processData: false,
processData
默认设置为 true
并假设传递的数据是一个对象,将其设置为 false
将阻止默认解析行为 - 这是你不想要的!在想要发送原始 JSON 的情况下这可能很好,但这与表单数据不同。
contentType
也以 application/x-www-form-urlencoded
形式传递。如果您将 contentType
设置为 false
,则您不会设置任何内容 header !因此,通过删除这两个值,您将拥有成功发送 ajax 调用的正确默认值。
关于php - 我无法从 Laravel 中的请求 AJAX 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61333587/