gpt4 book ai didi

javascript - jQuery Ajax 从 php 返回一些值

转载 作者:行者123 更新时间:2023-11-28 19:29:04 24 4
gpt4 key购买 nike

我使用 ajax 从 php 文件中挑选错误,但遇到了一些麻烦。就像在 php 文件中一样,我将错误放入 $email_error 和 $password_error 中,因此我想将错误报告返回到 ajax 并将 $email_error 分配给 id = "email_errors"并将 $password_error 分配给 id = "password_errors"。也许有人可以解释我如何指定我想要返回哪些变量以及它应该采用什么id。我将在下面留下一些注释代码。谢谢!

php

<?php


if (isset($_POST['email']) && isset($_POST['password1']) && isset($_POST['password2'])) {

$email = trim ($_POST['email']);
$password1 = trim ($_POST['password1']);
$password2 = trim ($_POST['password2']);

}

$email_error = 'No errors<br>';
$password_error = 'No errors<br>';

if (empty($email))
$email_error = ('Pleas fill in email field<br>');

if ($email == 'example')
$email_error =('There already is user with this email<br>');

if (empty($password1))
$password_error = ('Please fill in password fields<br>');

if (empty($password2))
$password_error = ('Please fill in password fields<br>');

$email_error; //this variable must be returned to ajax and assigned to id "email_errors"
$password_error; //this variable must be returned to ajax and assigned to id "password_errors"

?>

JavaScript

$(document).ready(function ()   {

$('#push_button').click(function() {

$.post('php.php',
{
email : $('#email').val(), // i take these variables to php
password1 : $('#password1').val(),
password1 : $('#password2').val()
} ,
function ( data ) { //what do i return here?

$('#email_errors').val(data); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data); //how to assign $password_error to #password_errors

}
)
})


})

最佳答案

要返回值,只需使用 json_encode() 回显变量例如

$return_array = new array();
$return_array['email_error'] = $email_error;
$return_array['password_errors'] = $password_errors;
echo json_encode($return_array);

在 JavaScript 函数(数据)中{}:

function ( data ) { //what do i return here?

$('#email_errors').val(data['email_error']); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data['password_errors']); //how to assign $password_error to #password_errors

}

关于javascript - jQuery Ajax 从 php 返回一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27250973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com