[英]passing parameters to a php from javascript
我之前已經做過,但是由於某種原因,參數被奇怪地傳遞了。
我有一個用於傳遞參數的javascript函數,已經運行了一些測試,並且該函數中的變量正確。
這些只是與該問題有關的js的一些摘要:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
我運行了一個網絡控制台,這實際上是通過的……
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
我不確定xmlhttp.open和php中的GET方法之間發生了什么。 這些變量都沒有傳遞。
為什么不使用jQuery-非常簡單的格式(我更喜歡POST ...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
請注意, success
回調函數的編寫非常簡單... subTask.php返回的任何內容都將在該函數中可用,如alert()示例所示。
只要記住在<head>
標簽中包含jQuery庫即可:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
另外,將此行添加到subTask.php
文件的頂部,以查看發生了什么:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
q=
和w=
的值將在警報框中返回給您,以便(至少)您可以看到subTask.php收到它們時所包含的值
以下腳本應有幫助:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.