[英]post data to PHP page in external server and load content from JavaScript in local computer
我想使用計算機/移動應用程序中的JavaScript將數據發布到服務器(www.domaine.com)中的PHP文件中
示例:test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
使用JavaScript和PSOT方法將數據發布到test.php
例
input
test.php / post data : count=5
output
01234
我希望JavaScript在將(count = 5)發布到位於外部服務器(www.domaine.com)的(test.php)后為我提供輸出(01234)
我基本上是用C#開發的,但是由於我不得不做一個跨平台的移動應用程序,因此我將C#切換為JavaScript(不會使用Xamarin),因此我可以使用WebBrowser來完成所有工作,但現在JavaScript中不再可用了,任何與.NET中的WebBrowser等效的對象?
我需要一個移動應用程序,它將從GPS跟蹤網站加載數據,API以XML和JSON形式返回數據
注意:我無權訪問外部服務器
在這里,我將為您提供一個很好的示例,說明通常如何管理這些內容。
盡管如此,掌握它的含義仍取決於您和您的編程經驗。
html和js示例:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php示例:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
痘痘:
type="number"
。 span
而不是input
是個人選擇,僅出於樣式目的而有所不同。 編輯:
這是$ less版本。
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.