PHP不接收来自Ajax请求的参数

时间:2016-02-21 20:51:09

标签: javascript php jquery html ajax

我想调用改变HTML文件内容的PHP脚本。

首先,我有一个带按钮的HTML。当我单击此按钮时,它会调用一个javascript函数,该函数会将一些参数发布到PHP脚本。此脚本将获取参数并生成将在HTML中显示的内容。

1)首先,我有表格标签,发送邮件动作到PHP。我从HTML中删除了此表单标记。

2)然后,我调用jsFunction()" javascript函数"点击"运行" HTML中的按钮。

onclick="jsFunction();"

3)我创建了javascript函数:

jsFunction(){
    var url = "calculateResult.php";
    var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             // change the content of the div in second tab
            document.getElementById("result").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("POST", url+"?"+params, true);
    xhttp.send();
}

4)PHP文件通过echo语句发送重播到javascript。

现在,我认为PHP没有从javascript函数接收任何参数!

我的代码中有什么问题吗?

修改1:

php中的一个步骤是生成文本文件并放入其中一个参数" querySeq"在那个文件中。当我打开文件时,它是空的。

PHP文件:

<?php

include("C:/inetpub/wwwroot/webclient/js-i2b2/cells/plugins/examples/BLAST/assets/include/path.inc");

$jobid = (empty($_GET['jobid'])) ? '' : $_GET['jobid'];
$blastdb = (empty($_POST['blastdb'])) ? '' : $_POST['blastdb'];
$blastpath = (empty($_POST['blastpath'])) ? '' : $_POST['blastpath'];
$patientIDarray = (empty($_POST['patientIDarray'])) ? '' : $_POST['patientIDarray'];
$opt = (empty($_GET['opt'])) ? '' : $_GET['opt'];
$blast_flag = (empty($_POST['blast_flag'])) ? 1 : $_POST['blast_flag'];
$filter_flag = (empty($_POST['filter_flag'])) ? '' : $_POST['filter_flag'];
$filt_val = (empty($_POST['filt_val'])) ? '' : $_POST['filt_val'];
$cutoffType = (empty($_POST['cutoffType'])) ? '' : $_POST['cutoffType'];
$pct_cutoff = (empty($_POST['pct_cutoff'])) ? '' : $_POST['pct_cutoff'];
$blst_cutoff = (empty($_POST['blst_cutoff'])) ? '' : $_POST['blst_cutoff'];
$searchType = (empty($_POST['searchType'])) ? '' : $_POST['searchType'];
$program = (empty($_POST['program'])) ? '' : $_POST['program'];
$dot = (empty($_GET['dot'])) ? '' : $_GET['dot'];
$querySeq = (empty($_POST['querySeq'])) ? '' : $_POST['querySeq'];
$blastagainstfile = (empty($_FILES['blastagainstfile']['name'])) ? '' : $_FILES['blastagainstfile']['name'];
$alignmentView = (empty($_GET['alignmentView'])) ? '' : $_GET['alignmentView'];

if ($blast_flag == 1) {
    $jobid = time().rand(10, 99);
}
if (!$blast_flag && !$jobid) {
    echo "<p>Error: No job submitted.</p>"; 
    footer();
    exit;
}

if ($searchType == 'advanced') {
    $expect=(empty($_POST['expect'])) ? 10 : $_POST['expect'];
    $wordSize = (empty($_POST['wordSize'])) ? '' : $_POST['wordSize'];
    $targetSeqs = (empty($_POST['targetSeqs'])) ? '' : $_POST['targetSeqs'];
    $mmScore = (empty($_POST['mmScore'])) ? '' : $_POST['mmScore'];
    $matrix = (empty($_POST['matrix'])) ? '' : $_POST['matrix'];
    $gapCost = (empty($_POST['gapCost'])) ? '' : $_POST['gapCost']; 
    $filter = (empty($_POST['filter'])) ? 'F' : $_POST['filter'];
    $softMask = (empty($_POST['softMask'])) ? 'F' : $_POST['softMask'];
    $lowerCaseMask = (empty($_POST['lowerCaseMask'])) ? 'F' : $_POST['lowerCaseMask'];
    $ungapAlign = (empty($_POST['ungapAlign'])) ? 'F' : $_POST['ungapAlign'];
    $alignmentView = (empty($_POST['outFmt'])) ? 0 : $_POST['outFmt'];  
    $geneticCode = (empty($_POST['qCode'])) ? '' : $_POST['qCode'];
    $dbGeneticCode = (empty($_POST['dbCode'])) ? '' : $_POST['dbCode'];
    $otherParam = (empty($_POST['OTHER_ADVANCED'])) ? '' : $_POST['OTHER_ADVANCED'];    
    if ($otherParam) {
        if (!preg_match("/^\s+$/", $otherParam) && !preg_match("/^\s*\-[A-Za-z]/", $otherParam)) {
            echo "Error: The other advanced options must start with \"-\"";
            exit;
        }
    }   
    $advanceParam = "$expect!#%$wordSize!#%$targetSeqs!#%$mmScore!#%$matrix!#%$gapCost!#%$filter!#%$softMask!#%$lowerCaseMask!#%$ungapAlign!#%$alignmentView!#%$geneticCode!#%$dbGeneticCode!#%$otherParam";
}else {
    $advanceParam = "";
}

if (!$alignmentView) {
    $alignmentView = 0;
}

if($blast_flag == 1) {
    $nlstr = chr(10);
    $crstr = chr(13);

    if($querySeq || !preg_match("/^\s+$/", $querySeq)) {
        @ $fp1=fopen("$dataPath/$jobid.blastinput.txt", "w",1);
        if (!$fp1)
        {
            echo "<p><strong> Error: couldn't open $dataPath/$jobid.blastinput.txt </strong></p></body></html>";
            exit;
        }

        fwrite($fp1, $querySeq);
        fclose($fp1);
    }else {
        echo "<p style='color: red'>Error: please enter your query sequence or upload your fasta sequence file.</p><br>";
        exit;
    }




}

if($cutoffType == 'pct') {
    $criterion = $pct_cutoff;
}
if($cutoffType == 'blst') {
    $criterion = $blst_cutoff;
}

if(!$opt || $opt == 'wait') {
    $progressdot = "image/progressdot.png";
    echo "<p><strong>Your job is being processed ";
    for($i = 0; $i <= ($dot%6); $i++) {
        echo "<img src='$progressdot'>";
    }
    echo "</strong></p>";
    $dot += 1;
    echo "<p>Your job id is $jobid.</p>";
    echo "<p>Please wait here to watch the progress of your job.</p>";
    echo "<p>This page will update itself automatically until search is done.</p>";     
}

if(!$opt || $opt == 'wait') {
    echo "<META HTTP-EQUIV=\"refresh\" 
    content=\"10;URL=blastresult.php?jobid=$jobid&alignmentView=$alignmentView&opt=wait&dot=$dot\">";
    echo "<META HTTP-EQUIV=\"expires\" 
          CONTENT=\"now\">";
}

if($blast_flag == 1) {  
    $blastagainst = "";
    if ($program == "blastn" || $program == "tblastn" || $program == "tblastx") {
        $dbPath = "C:/inetpub/wwwroot/webclient/db/nucleotide";
    }else {
        $dbPath = "C:/inetpub/wwwroot/webclient/db/protein";
    }

    if($blastagainstfile) {
        $blastagainst = "$dataPath/$jobid.blastagainst.txt";
    }

    if ($patientIDarray) {
        for ($i = 0; $i < sizeof($patientIDarray); $i++) {
            $blastagainst .= " $dbPath/$patientIDarray[$i]";            
        }
    }
    $blastpath = "C:/inetpub/wwwroot/webclient/blast/bin";
    $basicParam = "$jobid\t$searchType\t$blastagainst\t$program\t$blastpath";

    /*create child process to run perl script which do the blast search and write output data to apropriate files*/
    /* For windows */
    pclose(popen("start /b perl blast.pl \"$basicParam\" \"$advanceParam\"", "r"));
}


/* error log if there is error in BLAST */
$errFile = "$dataPath/$jobid.err";
/* parent process continue here to check child process done or not */
$filename = "$dataPath/$jobid.blaststring.txt";
if (file_exists($errFile) && filesize($errFile) > 0) {
    if(!$opt || $opt == 'wait') {
        echo "<script LANGUAGE=JavaScript>";
        echo "location.replace('blastresult.php?jobid=$jobid&opt=none')";
        echo "</script>";
    }else {
        echo "<p>There is error in executing BLAST. Following is the error message:<p>";
        $fperr = fopen("$dataPath/$jobid.err", "r");
        if(!$fperr) {
            echo "<p><strong> $jobid.err error: $errors  </strong></p></body></html>";
            exit;
        }

        while (!feof($fperr))
        {
            $line = rtrim(fgets($fperr)); 
            echo "$line<br>";
        }
        fclose($fperr);
    }   
}elseif(file_exists($filename)) {
    if ($alignmentView) {
        echo "<script LANGUAGE=JavaScript>";
        echo "location.replace('data/$jobid.blast')";
        echo "</script>";
    }else {
        if($blast_flag == 'Parse again') {
            $print_flag = 0;
            $cutoff_count = 0;

            @ $fpout=fopen("$dataPath/$jobid.par", "r");
            if (!$fpout)
            {
                echo "<p><strong> $jobid.par error: $phperrormsg  </strong></p></body></html>";
                exit;
            }

            @ $fpout3 = fopen("$dataPath/$jobid.out.par", "w", 1);
            if(!$fpout3) {
                echo "<p><strong> $jobid.out.par error: $errors  </strong></p></body></html>";
                exit;
            }

            while (!feof($fpout))
            {
                $fpout2_str = '';
                $line = rtrim(fgets($fpout));
                if (!$line) {
                    continue;
                }
                list($page, $query_name, $match_name, $score, $identities, $percentage, $e_value, $link) = preg_split("/\t/", $line);

                if($cutoffType == 'pct') {
                    $subject = $percentage;
                }else {
                    $subject = $score;
                }

                if($subject >= $criterion) {
                    fwrite($fpout3, "$page\t$query_name\t$match_name\t$score\t$identities\t$percentage\t$e_value\t$link\n");
                    $cutoff_count++;
                }
            }

            fclose ($fpout);
            fclose($fpout3);

            @ $fp = fopen("$dataPath/$jobid.blastcount.txt", "w", 1);
            if(!$fp) {
                echo "<p><strong> error: $php_errormsg  </strong></p></body></html>";
                exit;
            }else {
                fwrite($fp, "$cutoff_count\n");
            }

            fclose($fp);
        }

        $filename = "$dataPath/$jobid.blastcount.txt";

        while(!file_exists($filename)) {}

        if(!$opt || $opt == 'wait') {
            echo "<script LANGUAGE=JavaScript>";
            echo "location.replace('blastresult.php?jobid=$jobid&opt=none')";
            echo "</script>";
        }else {
            @ $fp = fopen("$dataPath/$jobid.blastcount.txt", "r");
            if(!$fp) {
                echo "<p><strong> error: $php_errormsg  </strong></p></body></html>";
                exit;
            }

            if(!feof($fp)) {
                $cutoff_count = fgets($fp);
            }
            fclose($fp);

            @ $fp = fopen("$dataPath/$jobid.blaststring.txt", "r");
            if(!$fp) {
                echo "<p><strong> error: $php_errormsg  </strong></p></body></html>";
                exit;
            }

            if(!feof($fp)) {
                $blastagainststring = rtrim(fgets($fp));
            }
            fclose($fp);

            if($cutoff_count == 0) {
                echo "<p>No comparison meets cutoff criterion. Please change expect value to blast again.</p>";
            }else {
                echo "<p><a href=data/$jobid.blast1.html target='_blank'>Inspect BLAST output</a><br>";         
                echo "<form action='blastresult.php?jobid=$jobid&opt=$opt' method='post'>";     
                echo "<p>Filter current page by score:</p>";
                echo "<p>&nbsp;&nbsp;&nbsp;Show <select name='filt_val'>";
                echo "<option value='0' selected>- All -";
                echo "<option value='1'>Top score";
                echo "<option value='5'>Top 5 scores";
                echo "<option value='10'>Top 10 scores";
                echo "</select> for each query sequence <input type='submit' name='filter_flag' value='Filter'></font></p>";                
                echo "<p>Re-parse current blast results (please select cutoff criterion):</p>";
                echo "<p><table style='font-size: 12px'>";
                echo "<tr><td><input type='radio' checked name='cutoffType' value='pct'>Similarity percentage</td><td></td>";
                echo "<td>Cutoff %: </td><td><input type='text' name='pct_cutoff' value=95 size=6 maxlength=6></td></tr>";              
                echo "<tr><td><input type='radio' name='cutoffType' value='blst'>Blast score</td><td></td>";        
                echo "<td>Cutoff score: </td><td><input type='text' name='blst_cutoff' value=1000 size=6 maxlength=6></td>";
                echo "<td><input type='submit' name='blast_flag' value='Parse again'>";             
                echo "</td></tr></table></p>";
                echo "</form>";     
                echo "<form action='sequence.php?jobid=$jobid' method='post' target='_blank' onsubmit=\"return checkform(this);\">";
                echo "<p>Retrieve and download subject sequences in FASTA format:</p>";     
                echo "<p><input type='checkbox' name='dldseq' value='all'>  Check here to download All sequences... ";
                echo "OR select particular sequences of interest below</p>";    
                echo "<p><input type='submit' value='Submit'> your selection of sequences to download</p>"; 
                echo "<p><table border = 1 style='font-size:10px' width=100% class='sortable'>";
                echo "<thead><tr align='center'><th>Query</th><th>Subject</th><th>Score</th><th>Identities (Query length)</th><th>Percentage</th><th>Expect</th></tr></thead>";
                echo "<tbody>";
                @ $fp = fopen("$dataPath/$jobid.download.txt", "w", 1) or die("Cannot open file: $jobid.download.txt");

                if($blast_flag == 'Parse again' || ($opt == 'none' && !$filter_flag)) {
                    @ $fpout3=fopen("$dataPath/$jobid.out.par", "r");
                    if(!$fpout3) {
                        echo "<p><strong> error: $php_errormsg  </strong></p></body></html>";
                        exit;
                    }
                    $i = 0;
                    $queryName = $preQueryName = "";
                    while(!feof($fpout3)) {
                        $row = fgets($fpout3);
                        if (!$row) {
                            continue;
                        }
                        $element = preg_split("/\t/", $row);        
                        $page = $element[0];
                        $queryName = $element[1];
                        $target_name = $element[7];
                        $var_target = $page."\t".$element[1]."\t".$element[2];
                        if(count($element) != 1) {
                            if($queryName == $preQueryName) {
                                $i++;
                            }else {
                                $i = 0;
                            }

                            if($i < 10) {
                                echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
                                fwrite($fp, "$var_target\n");
                            }                   
                        }
                        $preQueryName = $queryName;
                    }
                    fclose($fpout3);
                }

                if($filter_flag == 'Filter')
                {
                    @ $fpout3=fopen("$dataPath/$jobid.out.par", "r");
                    if(!$fpout3) {
                        echo "<p><strong> error: $php_errormsg  </strong></p></body></html>";
                        exit;
                    }
                    $i = 0;
                    while(!feof($fpout3)) {
                        $row = fgets($fpout3);
                        if (!$row) {
                            continue;
                        }
                        $element = preg_split("/\t/", $row);
                        $page = $element[0];
                        $target_name = $element[7];
                        $var_target = $page."\t".$element[1]."\t".$element[2];
                        if(count($element) != 1) {
                            if($filt_val != 0) {
                                if($i == 0) {
                                    $query_name = $element[1];
                                    echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
                                    fwrite($fp, "$var_target\n");
                                    $i++;
                                }elseif($query_name == $element[1] && $i < $filt_val) {
                                    echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
                                    fwrite($fp, "$var_target\n");
                                    $i++;
                                }elseif($query_name != $element[1]) {
                                    echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
                                    $query_name = $element[1];
                                    fwrite($fp, "$var_target\n");
                                    $i=1;
                                }
                            }else {
                                echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
                                fwrite($fp, "$var_target\n");
                            }
                        }
                    }
                    fclose($fpout3);
                }
                fclose($fp);
                echo "</tbody></table></form>";
                echo "<p><a href=\"#top\">Top</a>"; 
            }   
        }
    }   
}



?>

编辑2: 我尝试以下var varms:

var params = 'querySeq='+querySeq+'&program='+program+'&patientIDarray='+patientIDarray+'&blast_flag='+blast_flag;

OR

var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";

xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);

但是,它不起作用! HTML中的内容不会更改。 它仅在我指定时才有效:

var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";

xhttp.open("POST", url+"?"+params, true); 
xhttp.send();

但是,收到的参数是空的。

请帮忙。 谢谢,

编辑3:

它现在正在工作。我没有将参数从HTML传递到JS文件。只需通过onclick函数传递参数

 onclick=jsFunction(document.getElementById('some parameters').value)

我也使用:

var params = "querySeq="+querySeq+"&program="+program+"&patientIDarray="+patientIDarray

xhttp.open("POST", url, true);
        xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhttp.send(params);

它有效!

谢谢大家。

2 个答案:

答案 0 :(得分:1)

xhttp.open("POST", url+"?"+params, true);
xhttp.send();

您正在发出POST请求,暗示您正在$_POST中查找数据,但您已将所有数据放入查询字符串中。它需要进入请求体。

xhttp.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);

PHP将$_GET中的查询字符串中的数据和来自$_POST中的请求正文的数据(具有可识别的编码)放入。不幸的是,它将超全局变量命名为请求方法,其中这些位置通常用于存储数据,而不是基于数据的实际位置。

答案 1 :(得分:0)

工作GET示例:

<script>
function jsFunction() {
    var url = "receive.php";
    var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             // change the content of the div in second tab
            document.getElementById("result").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", url+"?"+params, true);
    xhttp.send();
}
</script>

工作POST示例:

<script>
function jsFunction() {
    var url = "receive.php";
    var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             // change the content of the div in second tab
            document.getElementById("result").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("POST", url, true);
    xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhttp.send(params);
}
</script>