用从php接收到的JS解析json数据
Parse json data with JS being received from php
我的表单:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
结束我的PHP脚本
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
我的页面正在接收如下数据:
{"status":0,"message":"This email is already on list!"}
使用JS,我需要解析这些数据,然后更新元素中的文本。
<span id="notice">Get notified!</span>
这是我的脚本,它不工作,后发送表单数据到我的php脚本,我得到一个白屏,显示json强
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
您必须在回调中处理响应。
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
请参阅此处的相关文档
ajax调用格式不正确,缺少成功回调和url,例如:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
您的代码是,只是在页面加载执行,而不是在提交表单。您需要附加一个onsubmit事件,防止默认的表单提交操作,并在其中执行ajax调用。此外,您的ajax调用本身是畸形的
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});
相关文章:
- 使用Angular.js解析JSON中的嵌套对象数组
- Knockout JS-解析/格式化值(extenders?)
- 带有Angular JS解析列表的picklest
- 使用 PEG.js 解析缩进级别
- 使用JS解析JSON文件(URL)
- 使用flash进行JS解析
- 使用 Date.js 解析 12 小时格式时获取 null
- 使用 D3.js 解析上传的 CSV 文件
- 主干.js解析未修改的响应
- 获取邮件中的信息.php从函数.js解析为manage.html
- 节点.js解析 fs.readFile() 的意外数字转换
- 节点.js解析路由的最小函数
- 使用 PEG.js 解析完整的数学表达式
- 仅使用 JS 解析 JS
- 骨干.js解析路由器中的可选页面查询字符串
- 检测车把.js解析/语法错误.(客户端模板化)
- PEG.JS解析逻辑变量名称,其操作数和值
- 如何使用 Math.js 解析器测试 MySQL 语法
- 通过 JS 解析 URL 参数,但仅将前八个字符作为值添加到 HTML 表单中
- JS:解析 x 的公式