简体   繁体   English

将 JavaScript 变量传递给 PHP 时遇到问题

[英]Trouble passing JavaScript variable to PHP

The solution to my problem now seems very basic.我的问题的解决方案现在看起来非常基本。 Although I understood php runs server-side I didn't know that that the php ran on pageload even if the include was nestled in the ajax callback.尽管我了解 php 在服务器端运行,但我不知道 php 在页面加载时运行,即使包含位于 ajax 回调中。 Although I could display the query results by returning the php in the javascript value attribute, if I didn't include the reference to the php script I got unterminated string errors.虽然我可以通过在 javascript 值属性中返回 php 来显示查询结果,但如果我没有包含对 php 脚本的引用,我就会得到未终止的字符串错误。 What I now realize is that (I think) the include caused the php to run before the ajax was fired which is why the php squawked about an undefined index.我现在意识到的是(我认为)包含导致 php 在 ajax 被触发之前运行,这就是为什么 php 抱怨未定义的索引。 Hard coding an ID into php would run fine since it didn't need anything from ajax to run the query.将 ID 硬编码到 php 中会运行良好,因为它不需要来自 ajax 的任何内容来运行查询。 Removing the include in the callback caused an undefined literal error because, having nothing to reference, the php broke causing the parser to see .value = " which is literally unterminated. By removing the php include and returning the query results via JSON, everything works perfectly. Seemed my road block was being stuck at how I learned to return php data to html. Anyway, valuable and useful lesson learned...删除回调中的包含会导致未定义的文字错误,因为没有任何引用,php 损坏导致解析器看到 .value = " 这实际上是未终止的。通过删除 php 包含并通过 JSON 返回查询结果,一切正常完美。似乎我的障碍被困在我如何学会将 php 数据返回到 html 上。无论如何,学到了宝贵而有用的教训......

The application is to pull log data, make modifications and save as a new or updated log file.该应用程序用于提取日志数据、进行修改并保存为新的或更新的日志文件。 The ajax sends an ID to the php script for the query to get the old info and populate each row cell. ajax 向 php 脚本发送一个 ID 以获取旧信息并填充每一行单元格。 The second cell (act-col) is dynamically loaded based on the selection in the first cell (reg-col).第二个单元格 (act-col) 根据第一个单元格 (reg-col) 中的选择动态加载。 To allow the user the ability to not only see the old info but also make changes, a second ajax call to get the right options is made.为了让用户不仅可以查看旧信息,还可以进行更改,进行了第二次 ajax 调用以获取正确的选项。 Anything already there is then emptied out and the new options are loaded.然后清空已经存在的任何内容并加载新选项。 This also makes sure that the select box is defined since, initially, until something is put in the the reg-col cell, the act-col cell is basically an empty box.这也确保了选择框的定义,因为最初,直到将某些内容放入 reg-col 单元格之前,act-col 单元格基本上是一个空框。 After that the rest of the cells are loaded with the old info, a new row is created and it loops through until all the info is displayed.在剩余的单元格加载旧信息之后,将创建一个新行并循环遍历直到显示所有信息。 Putting the add row function at the bottom of loop causes an extra row to be added but when the loop is completed I found that using javascript to delete it actually triggers all the math functions that occur as if the user creates a log from scratch.将 add row 函数放在循环底部会导致添加一个额外的行,但是当循环完成时,我发现使用 javascript 删除它实际上会触发所有发生的数学函数,就像用户从头开始创建日志一样。 Probably not the best solution but prevents having to pull data from another table to populate those fields on the initial button click.可能不是最好的解决方案,但可以防止必须从另一个表中提取数据以在初始按钮单击时填充这些字段。

Now that I understand it better I can clearly see all the suggestions pointing me to this.现在我对它有了更好的理解,我可以清楚地看到所有指向我的建议。 Oh, well...not the first time and surely not the last that hind site has humbled (and humiliated) me.哦,好吧......这不是第一次,当然也不是最后一次让我感到谦卑(和羞辱)我。 Here's what finally worked:这是最终有效的方法:

Here's the javascript/jquery:这是 javascript/jquery:

$(function(){
            $.ajax({
                  type:'POST',
                   url: 'phpScripts/lastSession.php',
              dataType: 'json',
                  data: {'id': pt_id},
                 cache:false,
               success:function(data){

        for(var j=0; j<data.length; j++){            

                    var reg=data[j].region;
                    $(".reg-col:eq("+j+")").val(reg);

                        if ((reg)==="knee/hip"){  $(function(){ $.ajax({
                                    url: 'phpScripts/getKneeHip.php',
                                    dataType: 'json',
                                    cache:false,
                                    async:false,
                                    success: function (json) {
                                        $(".act-col:eq("+j+")").empty().end();
                                        $.each(json, function(i, value) {
                                            $('<option>').text(value).attr('value', value).appendTo( $(".act-col:eq("+j+")"));

                                        });
                                    }
                                });
                            });
                        }//end if

                        else if ((reg)=="shoulder"){  $(function() { $.ajax({
                                    url: 'phpScripts/getShoulder.php',
                                    dataType: 'json',
                                    cache:false,
                                    async:false,
                                    success: function (json) {
                                        $(".act-col:eq("+j+")").empty().end()
                                        $.each(json, function(i, value) {
                                            $('<option>').text(value).attr('value', value).appendTo( $(".act-col:eq("+j+")"));

                                        })
                                    }
                                });
                            });

                        }//end if

                                            $(".act-col:eq("+j+")").val(data[j].activity);
                                            $(".reps-col:eq("+j+")").val(data[j].reps);
                                                   $(".weight-col:eq("+j+")").val(data[j].weights);
                                                   $(".prps-col:eq("+j+")").val(data[j].purposes);
                                                   $(".time-col:eq("+j+")").val(data[j].time);
                                                   $(".type-col:eq("+j+")").val(data[j].type);

                        addRow('dataTable');

          }
        document.getElementsByName("chk[]")[j].checked=true;
        document.getElementById('deleteBtn').click();

Here's the php:这是php:

      $ID = $_POST['id'];
  $return = array(); 
  $query = mysql_query("SELECT * FROM history WHERE patient_id = '$ID' AND date_of_service IN (SELECT MAX(date_of_service) FROM history WHERE patient_id = $ID)"); 
while ($row = mysql_fetch_array($query,MYSQL_ASSOC)) { 
array_push($return,array('region'=>$row['region'],'activity'=>$row['exercise'], 'reps'=>$row['reps'], 'weights'=>$row['weight'], 'purposes'=>$row['purpose'], 'time'=>$row['time'], 'type'=>$row['type'])); 
 } 
  header('Content-type: application/json');
  echo(json_encode($return)); 

You're trying to execute a server-side script phpScripts/lastSession.php on the client, which obviously isn't going to work.您正在尝试在客户端上执行服务器端脚本phpScripts/lastSession.php ,这显然是行不通的。 I'm not entirely clear on what you want to have happen there, but it seems like you would want that script to execute as part of your ajax call.我不完全清楚您希望在那里发生什么,但似乎您希望该脚本作为 ajax 调用的一部分执行。

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

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