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

Javascript PHP表单值作为回调函数中的JS变量,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我试图使用下面的代码在JS函数中传递php表单值-- 我就这样直接试过了-- mrp\u data\u回调.push(函数(索引、数据){ 数据[“”]=“”; 返回数据; }); 我遇到的问题是,这些值将不断更新,并使用其他js/ajax文件上的脚本进行处理。因此,试图直接在回调函数中回显php值是行不通的,我被告知在其他地方-- 混合使用PHP和JavaScript是行不通的(服务器端和客户端)。如果 htitle已更新,值将不会更新。例如,如果htitle是 “Hello”则回调函数始终

我试图使用下面的代码在JS函数中传递php表单值--

我就这样直接试过了--

mrp\u data\u回调.push(函数(索引、数据){
数据[“”]=“”;
返回数据;
});
我遇到的问题是,这些值将不断更新,并使用其他js/ajax文件上的脚本进行处理。因此,试图直接在回调函数中回显php值是行不通的,我被告知在其他地方--

混合使用PHP和JavaScript是行不通的(服务器端和客户端)。如果 htitle已更新,值将不会更新。例如,如果htitle是 “Hello”则回调函数始终为: mrp_data_callbacks.push(函数(索引,数据){data[“World”]= “世界”;返回数据;});回调函数应该是 填充表单上要在AJAX中提交的字段的值 要求因此,应该使用JavaScript而不是PHP来更新 HTML表单中的值

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

那么,我如何才能使这些值得到更新并使脚本正常工作呢

编辑

该表单由插件生成,相关代码如下所示--- --表单的模板


--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.');
    }
  });
});
if(isset($_POST['username'])){
    $username = escape($_POST['username']);
    $validate = new Validation();
    $validation = $validate->checkUniq('users', 'username', $username);
    $validation = ($validation == 0) ? 0 : 1;
    echo $validation;
}
<!-- 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>
<?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;
}
PHP:

$('#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.');
    }
  });
});
if(isset($_POST['username'])){
    $username = escape($_POST['username']);
    $validate = new Validation();
    $validation = $validate->checkUniq('users', 'username', $username);
    $validation = ($validation == 0) ? 0 : 1;
    echo $validation;
}
<!-- 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>
<?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;
}
使用jQuery可以提供如下函数,后两个函数是快捷方式

但是,如果您希望有大量用户使用表单处理相同的数据,而您又不断地将数据来回跳转给所有用户,这将给服务器带来大量负载


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

对于PHP,有,这个,还有这个,这不仅仅是针对PHP的



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

  • data.txt:-只是用来代替数据库进行演示

  • 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);
            }
        }
    });
    
    $(文档).ready(函数(){
    //为了初始化,我们在DOM准备就绪后调用fetchData函数
    //然后每10000毫秒重新调用一次,用新的
    //获取的数据,这些数据可能已被其他用户更改。
    fetchData();
    setInterval(fetchData,10000);
    //在任何按钮上单击,我们都会使用此值获得数值索引值
    //选择相应的标题和注释值,然后发送帖子
    //对foo.php的请求和我们称为updateHTML的响应数据
    $('.buttons')。在('click',function()上{
    indexV=$(this.attr('id').replace('btn-','');
    titleV=$('#mrp title-'+indexV).val();
    commentV=$('#comment-'+indexV).val();
    $.post('foo.php',{index:indexV,titleV,comment:commentV},函数(数据){
    如果(数据){
    更新HTML(数据);
    }
    });
    });
    //发出获取新数据的get请求
    函数fetchData(){
    $.get('foo.php',函数(数据){
    更新HTML(数据);
    });
    }
    //更新标题和注释输入值
    函数updateHTML(数据){
    变量titleID、titleV、commentID、commentV、indexV、content;
    //使用jQuery parseJSON函数转换JSON响应
    //到和数组,然后在此数组中循环以更新输入
    //使用新的标题和注释值。
    content=$.parseJSON(数据);
    对于(变量i=0;i
  • HTML:

    $('#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.');
        }
      });
    });
    
    if(isset($_POST['username'])){
        $username = escape($_POST['username']);
        $validate = new Validation();
        $validation = $validate->checkUniq('users', 'username', $username);
        $validation = ($validation == 0) ? 0 : 1;
        echo $validation;
    }
    
    <!-- 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>
    
    <?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;
    }
    
    
    标题#0:
    评论#0:
    保存更改
    
    标题#1: 评论#1: 保存更改
    标题#2: 评论#2: 保存更改
  • foo.php:

    $('#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.');
        }
      });
    });
    
    if(isset($_POST['username'])){
        $username = escape($_POST['username']);
        $validate = new Validation();
        $validation = $validate->checkUniq('users', 'username', $username);
        $validation = ($validation == 0) ? 0 : 1;
        echo $validation;
    }
    
    <!-- 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>
    
    <?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;
    }
    

    正如正确告诉您的那样,您仅从输入字段获取一次值(首次加载页面时,它将设置
    titleV
    commentV
    的值)。因此,如果用户操作改变了表单中的任何内容,那么它就不存在了。您需要在回调函数中移动获取
    titleV
    commentV
    的代码部分。因此,在动态调用函数时,它将始终从输入中获取当前值。类似这样的东西(有点改进)-

    
    var序列=”;
    mrp\u数据\u回调.push(函数(索引、数据){
    var titleV=document.getElementById(“mrp标题-”+序列).value;
    数据[“htitle-”+序列]=titleV;
    返回数据;
    });
    mrp\u数据\u回调.push(函数(索引、数据){
    var commentV=document.getElementById(“comment-”+sequence).value;
    数据[“注释-”+顺序]=commentV;
    返回数据;
    });
    
    您是否尝试使用PHP生成整个JS代码?这可能会起作用:

    <?php
    $js  = "<script type='text/javascript'>";
    $js += "var sequence = " . $sequence . ";";
    $js += "mrp_data_callbacks.push(function(index, data) {";
    $js += "    data[" . $key . "] = " . $value . ";";
    $js += "    return data;";
    $js += "});";
    $js += "</script>";
    echo $js;
    ?>
    
    有点让人困惑