返回php变量

Return php variable?

本文关键字:变量 php 返回      更新时间:2023-09-26

我为我的网站制作了一个小的AJAX脚本,它在提交时执行另一个文件中的php脚本。我设法用AJAX函数回显了原始文件中的结果,但我没有设法将一个变量从php文件传输到原始文件。

我需要这个变量来添加一个事件侦听器,该侦听器将查找该特定变量中的更改(也不确定如何执行)。

以下是您正在寻找的工作原理:-把这个放在你的forsok.php 中

<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
 $.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
 alert(data['show']);
 $('#show_result').text(data['show']);
}else{
 alert('Nothing');
}
});
}
});
</script>

对于hej.php:-

<?php

$one=$_GET['number'];
if(empty($one)) {
    echo "Can't be blank";
    $a['result']='null';
    $a['error'] = 'No value!!';
} else {
    if(is_numeric($one)) {
        $show=$one*2;
        $arr = array(
        'show'=>$show
        );
        header('Content-Type:application/json');
        echo json_encode($arr);
        exit();
       // echo $show;
    } else {
        echo "NaN";
        $a['result']='null';
        $a['error']='nan';
    }

}
?>

首先创建一个应该作为输出的数组。JSON对该数组进行编码,然后可以在ajax成功处理程序中解析输出。在php文件中输出类似:

echo json_encode(array(
    'result' => 'null',
    'error' => 'nan'
));

然后,在ajax成功的情况下,将json转换为一个对象,并根据需要解析数据:

success: function (data, textStatus, jqXHR) {
    var obj = $.parseJSON(data);
    $('#utmatning').html(obj.result); // result value from your json return
    $('#utmatning').append(obj.error); // error value from your json return
}

在php文件的最后添加

json_encode($a);

在ajax的成功中,

success: function(html) {
    $.each(html, function(index, element) {
        alert(element.result);
        alert(element.error);
        //append to which ever div you want.
    });
}

现在,您可以从php

中获得n数量的数组索引

与其在hej.php中到处回显字符串,不如将JSON数据返回到ajax调用。因此,您可以评估是否发生了错误,是哪个错误或返回了哪个有效结果。

hej.hp:

<?php
    $one=$_GET['value'];
    if(empty($one)) {
        $a['result']='null';
        $a['error'] = 'No value!!';
    } else {
        if(is_numeric($one)) {
            $a['result']=$one*2;
            $a['error']='ok';
        } else {
            $a['result']='null';
            $a['error']='nan';
        }
    }
    die(json_encode ($a));
?>

如果$value为1,则返回

{"result":"2","error":"ok"}

在forsok.php中,您可以检查重复使用并采取相应的

...
$.ajax({
    type: "GET",
    dataType: "json",
    url: url,
    data: $("#idForm").serialize(), // serializes the form's elements.
    success: function(response)
    {
        if (response.error=='ok'){
            $('#utmatning').html(response.result); // show response from the php script.
        }
        else{
            console.log(response.result); // handle the error
        }
    }
});
...

谨致问候,Stefan