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

Ric*_*ich 9 html javascript php ajax jquery

我试图使用以下代码在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>
Run Code Online (Sandbox Code Playgroud)

得到这样的东西 -

jQuery(document).ready(function() { 
mrp_data_callbacks.push( function(index, data) {
data["hello"] = "world";
return data;
});
});
Run Code Online (Sandbox Code Playgroud)

我直接尝试这样 -

 mrp_data_callbacks.push( function(index, data) {
        data["<?php echo "htitle-" . $sequence ?>"] = "<?php echo $htitle ?>";
        return data;
    });
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是值将不断更新并使用其他js/ajax文件上的脚本进行处理.所以试图直接在回调函数中回显php值没有工作,我被告知在哪里 -

混合PHP和JavaScript不会工作(服务器端与客户端).如果更新了htitle,则不会更新这些值.例如,如果htitle是"Hello",则回调函数将始终为:mrp_data_callbacks.push(function(index,data){data ["World"] ="World"; return data;}); 回调函数应该填充表单上的字段值以在AJAX请求中提交.因此,您应该使用JavaScript而不是PHP来从HTML表单中获取更新的值.

实际上,如果您有一个用户填写的HTML表单,那么在提交表单之前,PHP不知道这些修改后的值.PHP仅在传递给服务器时执行某些操作,而不是在用户滚动浏览网页时填写文本.那么在这种情况下你应该使用javascript.

那么我怎样才能使这些值更新并且脚本有效呢?

编辑

表单由插件生成,相关代码可以在下面看到--- http://pastebin.com/RrjJqaFB - 表单的模板

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

Mi-*_*ity 8

这可以用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.');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

使用jQuery给你喜欢的功能$.ajax(),$.post(),$.get(),后两个功能快捷键.

但是,如果您期望大量用户使用表单处理相同的数据,并且您不断向所有用户反弹数据,这会对服务器造成大量负担.


另一方面,Web WebSocket通过打开服务器和用户之间的连接通道来工作,这个连接通道保持打开状态,直到用户断开连接,不知何故这对服务器没有太多负担,我还没有使用WebSocket但是我我们已经阅读了几篇文章,并在YouTube上观看了一些视频,其中大部分内容都是关于创建实时聊天应用或多用户网页游戏.

对于PHP,有这个PHP-Websockets和这个Ratchet库,这个WebSockets也是UNIX方式,不仅适用于PHP.



更新1: 根据OP的评论,让我们假设我们有一个类似但更简单的情况,在同一文件级别上有以下文件:

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

    title 0 , comment number 0
    title 1 , comment number 1
    title 2 , comment number 2
    
    Run Code Online (Sandbox Code Playgroud)
  • 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);
            }
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 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>
    
    Run Code Online (Sandbox Code Playgroud)
  • 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

对于上面的文件,一旦DOM准备就绪,我们fetchData()第一次调用输入值来使用来自databas - data.txt的数据.在这个例子而不是简单的数据库 - 然后我们fetchData()使用javascript每10秒调用一次setInterval(),这样如果userX改变了一些输入值,所有其他用户将在10秒后看到他们的屏幕上的结果更新,假设10秒是足够的,它可能不到10秒,但用户没有时间更改一个输入值,也就是你把更多负载放在服务器上的时间越短,反之亦然.

如果您在测试服务器上创建具有相同代码的相同文件结构 - 例如localhost - 并打开包含Chrome中所有输入字段和按钮的网页 - 作为 userX - 和Firefox - 作为 userY - 和IE - 作为 userZ - 例如,更改其中一个输入字段的值并点击相应的"保存更改" button,让我们说"Chrome",你会看到相同字段的值在"Firefox"和"IE"中自动更新10秒后自动.

所以,你可以让你的PHP echo的假设$result数组 json_encode它就像在我的例子,在JavaScript中,首先使用jQuery $.parseJSON()函数将JSON对象转换成一个数组遍历结果并推动各行值的mrp_data_callbacks,这就是它!