简体   繁体   English

如何使用json将响应从php返回到javascript?

[英]how to get the response back to javascript from php using json?

THIS ISSUE HAS BEEN SOLVED 此问题已得到解决

THE BELOW CODE IS THE CORRECTED AND WORKING CODE 下面的代码是正确的工作代码

I have created a html form which sends certain variables to a php file and returns the success through json back to the javascript. 我创建了一个html表单,该表单将某些变量发送到php文件,并通过json将成功返回给javascript。 But the problem is am not able to get any response back to the javascript file. 但是问题是无法获得对javascript文件的任何响应。 I donno what is the reason. 我不知道是什么原因。 So can some help me with this. 所以有些可以帮助我。 Thank you 谢谢

my form is 我的表格是

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">       </script>
<script src="scriptj.js"></script>
</head>
<body>
<form action="http://localhost/donotdel/process.php" method="POST">
    <div id="name-group" class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" name="name" placeholder="name">
    </div>
    <div id="email-group" class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" name="email" placeholder="email">
    </div>
    <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
  </form>
</body>
</html>

my javascript file is 我的JavaScript文件是

$(document).ready(function () {
    $('form').submit(function (event) {
        $('.form-group').removeClass('has-error');
        $('.help-block').remove();
        var formData = {
            'name': $('input[name=name]').val(),
            'email': $('input[name=email]').val(),
        };
        $.ajax({
            type: 'POST',
            url: 'http://localhost/donotdel/process.php',
            data: formData,
            dataType: 'json',
            encode: true
        }).done(function (data) {
            console.log(data);
            if (!data.success) {
                if (data.errors.name) {
                    $('#name-group').addClass('has-error');
                    $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
                }

                if (data.errors.email) {
                    $('#email-group').addClass('has-error');
                    $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
                }
            }
            else {
                $('form').append('<div class="alert alert-success">' + data.message + '</div>');
            }
        }).fail(function (data) {
            console.log(data);
        });
        event.preventDefault();
    });
});

and my php file is 和我的PHP文件是

<?php

$errors         = array();      
$data           = array(); 

if (empty($_POST['name']))
    $errors['name'] = 'Name is required.';

if (empty($_POST['email']))
    $errors['email'] = 'Email is required.';

if ( ! empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
}
header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);
?>

the error that i am getting is instead of passing the json to javascript file, the json is printed in the screen. 我得到的错误不是将json传递给javascript文件,而是将json打印在屏幕上。 But whereas i need the javascript to show an alert. 但是,尽管我需要JavaScript来显示警报。

Try setting the proper header in php: 尝试在php中设置适当的标头:

header ('Content-Type: application/json');

Failing that - can you post a plunker or jsfiddle? 失败了-您可以发布一个punker或jsfiddle吗?

As discussed with OP. 正如与OP讨论的那样。

-> First error is jQuery library not loaded from goole server so suggest to download latest jQuery library ->第一个错误是未从goole服务器加载jQuery库,因此建议下载最新的jQuery库

-> second error is 'Access-Control-Allow-Origin' . ->第二个错误是'Access-Control-Allow-Origin' suggest to add header ('Content-Type: application/json');header("Access-Control-Allow-Origin: *"); 建议添加header ('Content-Type: application/json');header("Access-Control-Allow-Origin: *"); in php file or make sure to call ajax request from same origin domain 在php文件中或确保从相同的原始域调用ajax请求

header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM