gpt4 book ai didi

javascript - PHP 表单值作为回调函数中的 JS 变量

转载 作者:太空狗 更新时间:2023-10-29 13:27:09 24 4
gpt4 key购买 nike

我正在尝试使用以下代码在 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() , 后两个函数是快捷键。

但是,如果您期望有大量用户使用表单处理相同的数据,并且您不断地向所有用户发送和返回数据,这会给服务器带来很大的负载。


另一方面网站WebSocket通过在服务器和用户之间打开一个连接 channel 来工作,这个连接 channel 保持打开状态直到用户断开连接,不知何故这不会给服务器带来太大的负载,我还没有使用过 WebSocket 但我已经阅读了几篇文章并观看了YouTube 上的视频很少,其中大部分是关于创建实时聊天应用程序或多用户网络游戏。

对于 PHP,有 this PHP-Websockets ,还有这个 Ratchet library , 还有这个 WebSockets the UNIX way这不仅适用于 PHP。



更新 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() 以使用来自数据库 -data.txt 的数据填充输入值。在此示例中,为了简单起见,我们使用 javascript setInterval() 每 10 秒调用一次 fetchData(),这样如果某些输入值具有已被 userX 更改,所有其他用户将在 10 秒后在他们的屏幕上看到更新的结果,假设 10 秒就足够了,可能少于 10 秒但用户没有时间更改一个输入值均匀,而且你放置的时间越短,你对服务器的负载就越大,反之亦然。

如果您使用与上述相同的代码在测试服务器上创建相同的文件结构 -例如 localhost - 并在 Chrome 中打开包含所有输入字段和按钮的网页 -as userX- 和 Firefox -as userY- 和 IE -as userZ-例如,更改其中一个输入字段的值并点击相应的“保存更改”的按钮,比方说“Chrome”,您会看到相同字段的值已更新为“Firefox"和 "IE"10 秒后自动。

所以你可以让你的 PHP echo 让我们说 $result 数组 AFTER json_encode 就像在在我的示例中,在 javascript 中,首先使用 jQuery $.parseJSON() 函数将 JSON 对象转换为数组循环并遍历结果并将每一行值推送到 mrp_data_callbacks ,就是这样!

关于javascript - PHP 表单值作为回调函数中的 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475276/

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