PHP表单值如何作为JS回调函数中的变量?

我正在尝试使用以下代码在JS函数中传递php表单值-

<script type="text/javascript">

var titleV = document.getElementById("mrp-title-<?php echo $sequence ?>").value;

var commentV = document.getElementById("comment-<?php echo $sequence; ?>").value;

mrp_data_callbacks.push( function(index, data) {

data["<?php echo "htitle-" . $sequence ?>"] = titleV;

return data;

});

mrp_data_callbacks.push( function(index, data) {

data["<?php echo "comment-" . $sequence ?>"] = commentV;

return data;

});

</script>

为了得到这样的东西-

jQuery(document).ready(function() {

mrp_data_callbacks.push( function(index, data) {

data["hello"] = "world";

return data;

});

});

我直接尝试过这样-

 mrp_data_callbacks.push( function(index, data) {

data["<?php echo "htitle-" . $sequence ?>"] = "<?php echo $htitle ?>";

return data;

});

我遇到的问题是这些值将不断更新并使用其他js/ajax文件上的脚本进行处理。因此,尝试直接在回调函数中回显php值没有用,并且我被告知其他地方-

mixing PHP and JavaScript wont work (server side vs. client side). If

htitle is updated, the values will not be updated. E.g. if htitle is

"Hello" then the callback functions will always be:

mrp_data_callbacks.push( function(index, data) { data["World"] =

"World"; return data; }); The callback function is supposed to

populate the values of the fields on the form to submit in the AJAX

request. So you should use JavaScript not PHP to get the updated

values from the HTML form.

Indeed, if you have an HTML form that the user fills in, then those

modified values are not known by PHP until the form is submitted. PHP

is only doing something when is passed to the server, not while the

user is scrolling through the web page, filling in text. So in that

case you should use javascript.

那么,如何使这些值更新并运行脚本呢?

编辑

该表格是由插件生成的,相关代码如下:

http://pastebin.com/RrjJqaFB-表单的模板

http://pastebin.com/tp8Gxv8B-Frontend.js-这是完成ajax和定义回调函数的地方。

最佳答案

可以使用AJAX或WebSocket来完成,而使用jQuery则可以实现以下功能:

JS:

$('#username').on('change input', function(){

var username = $(this).val();

// Here you send - post - data to the .php file which deals with as

// a regular post request, some thing could be said for $.get as GET request

$.post('check_username.php', { username : username}, function(data){

if(data == 1){

// if data was 1, means the php found that username already in

// the database and echoed 1 back

$(this).addClass('errorMsg').text('This username is already taken.');

}

});

});

PHP:

if(isset($_POST['username'])){

$username = escape($_POST['username']);

$validate = new Validation();

$validation = $validate->checkUniq('users', 'username', $username);

$validation = ($validation == 0) ? 0 : 1;

echo $validation;

}

使用jQuery可为您提供 $.ajax()$.post()$.get() 之类的功能,后两个功能是快捷方式。

但是,如果您期望大量的用户使用表单处理相同的数据,并且不断将数据跳回并返回给所有用户,这将给服务器带来很多负担。

另一方面,Web WebSocket通过打开服务器与用户之间的连接 channel 来工作,该连接 channel 一直保持打开状态,直到用户断开连接为止,以某种方式这不会给服务器带来太大的负担,我还没有使用WebSocket,但是我在YouTube上阅读了几篇文章,并观看了一些视频,其中大多数是关于创建实时聊天应用程序或多用户网络游戏的视频。

  • WebSockets Examples

对于PHP,有this PHP-Websockets,还有Ratchet library,还有不是仅用于PHP的WebSockets the UNIX way。

更新1:

根据OP的评论,让我们假设有一种类似但更简单的情况,以下文件都位于同一文件级别:

  • data.txt:-仅用于代替数据库进行演示

    title 0 , comment number 0

    title 1 , comment number 1

    title 2 , comment number 2

  • JS

    $(document).ready(function() {

    // for initializing we call fetchData function as soon as DOM is ready

    // then re-call it every 10,000 milliseconds to update the input values with new

    // fetched data , that could have been changed by other users.

    fetchData();

    setInterval(fetchData, 10000);

    // on any button click we get the numeric index value, using this value

    // to pick correspnding title and comment values, then send a POST

    // request to foo.php and on response data we call updateHTML

    $('.buttons').on('click', function(){

    indexV = $(this).attr('id').replace('btn-', '');

    titleV = $('#mrp-title-' + indexV).val();

    commentV = $('#comment-' + indexV).val();

    $.post('foo.php', { index : indexV, title:titleV, comment: commentV}, function(data){

    if(data){

    updateHTML(data);

    }

    });

    });

    // Making a get request to fetch fresh data

    function fetchData(){

    $.get('foo.php', function(data){

    updateHTML(data);

    });

    }

    // Update title and comment inputs values

    function updateHTML(data){

    var titleID, titleV, commentID, commentV, indexV, content;

    // using jQuery parseJSON function to convert the JSON response

    // to and array, then loop through this array to update inputs

    // with new title and comment values.

    content = $.parseJSON(data);

    for(var i = 0; i < content.length; i++){

    titleID = '#mrp-title-' + i;

    titleV = content[i].title,

    commentID = '#comment-' + i;

    commentV = content[i].comment;

    $(titleID).val(titleV);

    $(commentID).val(commentV);

    }

    }

    });

  • HTML:

    <!-- this is usually generated with PHP -->

    <div id="output">

    <label for="mrp-title-0">Title #0:</label>

    <input type="text" id="mrp-title-0" class="titles" value="">

    <label for="comment-0">Comment #0:</label>

    <input type="text" id="comment-0" class="comments" value="">

    <button id="btn-0" class="buttons">Save Changes</button>

    <hr>

    <label for="mrp-title-1">Title #1:</label>

    <input type="text" id="mrp-title-1" class="titles" value="">

    <label for="comment-1">Comment #1:</label>

    <input type="text" id="comment-1" class="comments" value="">

    <button id="btn-1" class="buttons">Save Changes</button>

    <hr>

    <label for="mrp-title-2">Title #2:</label>

    <input type="text" id="mrp-title-2" class="titles" value="">

    <label for="comment-2">Comment #2:</label>

    <input type="text" id="comment-2" class="comments" value="">

    <button id="btn-2" class="buttons">Save Changes</button>

    </div>

  • foo.php:

    <?php

    if(isset($_POST['index']) && isset($_POST['title']) && isset($_POST['comment'])){

    // if there's a POST request, we retrieve the data.txt content as an array

    // depending on the POST index value we change the corresponding item in

    // the array to update title and comment values, then write the array as

    // new content of the data.txt with the new array $foo.

    $index = $_POST['index'];

    $title = $_POST['title'];

    $comment = $_POST['comment'];

    //Do validation and sanitizing here

    $temp = '';

    $foo = getContent();

    $foo[$index]['title'] = $title;

    $foo[$index]['comment'] = $comment;

    for($i = 0; $i < count($foo); $i++) {

    $temp .= $foo[$i]['title'] . ' , ' . $foo[$i]['comment'] . "\n";

    }

    $temp = trim($temp);

    file_put_contents('data.txt', $temp);

    }else{

    // if no POST request, no changes happened and our array is same as file content

    $foo = getContent();

    }

    // we encode $foo as JSON and echo it back to javascript

    $jsonFoo = json_encode($foo);

    echo $jsonFoo;

    // getting data.txt content and return an array of the content

    function getContent(){

    $bar = array();

    $data = file_get_contents('data.txt');

    $rows = explode("\n", $data);

    foreach ($rows as $row) {

    $cols = explode(",", $row);

    $title = trim($cols[0]);

    $comment = trim($cols[1]);

    $bar[] = array('title' => $title, 'comment' => $comment);

    }

    return $bar;

    }

对于上面的文件,在DOM准备就绪后不久,我们第一次调用fetchData()用来自databas -data.txt的数据填充输入值。在此示例中,为简单起见,我们使用javascript fetchData()每10秒调用setInterval(),而不是简单的数据库,因此,如果 userX 更改了某些输入值,则所有其他用户将在10秒后在他们的屏幕上看到更新的结果,假设10秒就足够了,可能不到10秒,但是用户甚至没有时间更改一个输入值,而且时间间隔越短,服务器上的负载就越大,反之亦然。

如果您在测试服务器-例如localhost-上使用与上面相同的代码创建相同的文件结构,然后在Chrome中打开包含所有输入字段和按钮的网页-作为 userX -和Firefox-作为 userY -和IE -as userZ -例如,更改输入字段之一的值并在“Chrome”中打相应的“Save Changes”的button,您将看到在“Firefox”中该字段的值已更新,并且“IE”将在10秒钟后自动显示。

因此,您可以像在我的示例中那样将PHP echo设置为$result数组,然后像json_encode一样,在javascript中,首先使用jQuery $.parseJSON()函数将JSON对象转换为通过结果的数组循环,并将每行值插入mrp_data_callbacks ,就是这样!

以上是 PHP表单值如何作为JS回调函数中的变量? 的全部内容, 来源链接: www.h5w3.com/122586.html

回到顶部