Laravel 5 - Ajax POST - $request->all() 在 PostController 中返回空数组



很抱歉重复,但我尝试了每个问题的每一个建议,甚至模糊地与此相似,没有结束。

阿贾克斯帖子:

var contactForm = $('#contactForm');
contactForm.on('submit', (event) => {
event.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
}
})
console.log(contactForm.serializeArray())
$.ajax({
dataType: "json",
method : 'POST',
url : 'contact-us/post',
data : contactForm.serializeArray(),
success: (res) => {
console.log(res)
}
})
})

路线处理岗位:

Route::post('contact-us/post', 'EnquiryPostController@store');

后控制器存储方法:

public function store(Request $request)
{
return response()->json(['success'=>$request->all()]);
}

控制台输出

来自"网络"选项卡的响应标头

来自"网络"选项卡的请求标头

从"网络"选项卡中的数据

更新:

只是为了澄清:

  • 我正在传递 CSRF 令牌。
  • 表单输入具有名称属性。
  • 后控制器正在接收 POST 请求,但根本不包含任何表单数据。
  • 此问题发生在 AJAX POST 和常规旧窗体 POST 中

事实证明,这不是Laravel的问题,而是Windows Server/web.config的问题。我会使用此处找到的 XML 设置我的网站。经过多次试验和错误,使用以下XML解决了该问题:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<ModSecurity enabled="true" configFile="c:inetpubwwwrootmodsecurity.conf" />
<httpErrors errorMode="Detailed" />
<modules runAllManagedModulesForAllRequests="true" />
<defaultDocument>
<files>
<clear />
<add value="index.php" />
</files>
</defaultDocument>
<rewrite>
<rules>
<rule name="CanonicalHostNameRule1">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^dev.financialservicesexpo.co.uk$" negate="true" />
</conditions>
<action type="Redirect" url="http://dev.financialservicesexpo.co.uk/{R:1}" />
</rule>
<rule name="default" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.php" />
</rule>
</rules>
</rewrite>
<staticContent>
<clientCache cacheControlMaxAge="8.00:00:00" cacheControlMode="UseMaxAge"/>
</staticContent>
</system.webServer>
</configuration>

我希望我能解释为什么这解决了这个问题,但我对服务器配置知之甚少。如果有人想发表有见地的评论,我至少会觉得很有趣。

如果这没有帮助,请阅读以下内容

要深入了解这个问题,需要尝试许多不同的解决方案,这些解决方案是在发布到 StackOverflow 等的更多问题中找到的,最终在与同事聊天并大声解决问题后两分钟内得到解决。我一直需要学习的令人沮丧的教训......因此,希望这可能会对其他人有所帮助,以下是您应该检查的上述解决方案的列表。

  • 检查表单输入是否具有名称属性。
  • 清除浏览器缓存。
  • 清除拉拉维尔缓存数据。
  • 重启网站
  • 使用
  • AJAX 时,请尝试同时使用 serialize(( 和 serializeArray((
  • 使用
  • AJAX 时,请尝试使用不同的数据类型和内容类型提交。默认值应该没问题,但如果您做不同的事情,值得大喊大叫。
  • CSRF 令牌:通过隐藏的输入字段或在请求标头中设置添加它。只需要一个。
  • 确保/storage 和/bootstrap 文件夹已启用读/写权限。

如果有人对我在这里写的内容有任何建议或更正,请说出来。我绝不是专家。

尝试使用type而不是像method

$.ajax({
dataType: "json",
type : 'POST',
url : 'contact-us/post',
data : contactForm.serializeArray(),
success: (res) => {
console.log(res)
}
})

您可以使用以下解决方案发送数据:

data : contactForm.serialize()

最新更新