简体   繁体   English

通过Javascript函数返回PHP数据而无需提交表单

[英]Return PHP data via Javascript function without submitting form

I have a PHP function that accepts two dates and returns the number of business days between them (holidays included, because we pay out on those). 我有一个PHP函数,它接受两个日期并返回两个日期之间的工作日(包括假期,因为我们要付清这两个日期)。 Right now, I can call this function within a Javascript function and get a value back if I send the function real dates. 现在,我可以在Javascript函数中调用此函数,并且如果我发送该函数的实际日期,则可以返回一个值。 For example: 例如:

function daycount() {
var days="<?php echo getDays("01/01/2014","01/31/2014"); ?>";
document.write(days);
}

This returns 23, as expected. 如预期的那样返回23。 What I would like to have happen is for the user to be able to put start and end dates in two fields and then feed those field values to the above function, displaying the result without the user having to submit the form. 我想让用户能够将开始日期和结束日期放在两个字段中,然后将这些字段值提供给上述功能,而无需用户提交表单即可显示结果。 Something like this: 像这样:

 <label for="startDate">Start</label>
 <input type="text" name="startDate" id="startDate" onFocus="daycount();" />
 <label for="endDate">End</label>
 <input type="text" name="endDate" id="endDate" onFocus="daycount();" />

Is this possible? 这可能吗?

You don't need PHP for this, as you can do all of this with JavaScript. 您不需要PHP,因为您可以使用JavaScript来完成所有这些工作。 However if you want to use PHP then you can do it like this with AJAX in jQuery: 但是,如果您想使用PHP,则可以使用jQuery中的AJAX来做到这一点:

Input fields: 输入栏位:

<input type="text" name="startDate" id="startDate">
<input type="text" name="endDate" id="endDate">

jQuery: jQuery的:

$('form').submit(function(event) {
    var start = $('#startDate').val();
    var end = $('#endDate').val();

    $.ajax({
        type: 'POST',
        url: 'date.php',
        data: {
            startDate: start,
            endDate: end
        },
        success: function(data) {
            $('#result').text(data);
        }
    });

    event.preventDefault();
});

date.php: date.php:

<?php
    // You getDays function here    

    echo getDays($_POST['startDate'], $_POST['endDate']);
?>

PHP happens on server side, Javascript on client side. PHP发生在服务器端,JavaScript发生在客户端。 That means that your PHP script is happening before the javascript runs. 这意味着您的PHP脚本是在javascript运行之前发生的。 You can not just call PHP functions from a Javascript function because they happen at different times. 您不能仅从Javascript函数调用PHP函数,因为它们发生在不同的时间。

The best method of achieving what you are requesting will be using Ajax to communicate between your Javascript scripts and PHP scripts. 实现请求的最佳方法是使用Ajax在Javascript脚本和PHP脚本之间进行通信。 The other alternative will be posting with a form but that's not very 'web 2.0'... 另一种选择是使用表单发布,但这不是'web 2.0'...

Ajax request will look something like this (using jQuery): Ajax请求将如下所示(使用jQuery):

$.ajax({
url: "script.php",
method:'POST'
})
.success(function( data ) {
  //do your thing here with the returned data 
});

and you main code will look similar to this: 您的主代码将类似于以下内容:

function daycount() {
$.ajax({
    url: "script.php",
    method:'POST',
    data: {var1:'',var2:'', etc etc}
    })
    .success(function( data ) {
      var days = data;//depending on how you return the data from the php script
      document.write(days);
    });
}

Hope this helps! 希望这可以帮助!

I would do it using jQuery $.post sending two dates to php script which should return answer eg: 我会使用jQuery $ .post将两个日期发送到php脚本来完成,该脚本应返回答案,例如:

HTML: HTML:

<form id='days_form'>
    <input name='date_one' /> - <input name='date_two'/>
    <input type='button' id='sendBtn'>
</form>

<span id='answer'></span>

JavaScript: JavaScript:

$('#sendBtn').click(function{
    $.post('php_script_file.php', $('#days_form').serialize(), function(data){
        $('#answer').html(data);
    });
});

PHP file: PHP文件:

print getDays("$_POST['date_one']", $_POST['date_two']);

Not in this way. 不是这样。 What you must understand is that when the php renders the page from server the javascript part is written as 您必须了解的是,当php从服务器渲染页面时,javascript部分被编写为

function daycount() {
var days="23";
document.write(days);
}

This is why its working. 这就是为什么它起作用。 After it renders if you want the functionality to work then there are two ways. 渲染后,如果您希望功能正常工作,则有两种方法。

First one- if you want it to be done only from backend(php) then you need to make ajax call and get the results. 第一个-如果您希望仅从backend(php)完成,则需要进行ajax调用并获取结果。

Second one - If you want it to be done on client side , you should convert business login written in getDays($a,$b); 第二个-如果您希望在客户端完成此操作,则应转换以getDays($a,$b);编写的业务登录信息getDays($a,$b); Javascript. Javascript。

For the javascript date functionality try using moment.js 对于javascript日期功能,请尝试使用moment.js

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

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