简体   繁体   English

通过不带表格的帖子将javascript变量发送到php脚本

[英]sending javascript variable to php script via post without form

I know there are quite a few questions like mine, but I'm attempting to pass a javascript variable to a php script using AJAX. 我知道有很多类似我的问题,但是我正在尝试使用AJAX将javascript变量传递给php脚本。 Can anyone point out what I'm doing wrong? 谁能指出我做错了什么? Can't seem to figure it out. 似乎无法弄清楚。 My javascript on original page: 我在原始页面上的JavaScript:

var myvariable = document.documentElement.innerHTML;
// send variable to server via ajax here  
$.ajax({
   url: 'myphp.php',
   data: { myvariable : myvariable },
   type: 'POST',
   success: function(result) {
    alert("success!");
       }
});

and then to receive on the 'myphp.php' page: 然后在“ myphp.php”页面上接收:

<?php
if(isset($_POST['myvariable']))
{
$myvariable = $_POST['myvariable'];
}
?>

I'm trying to do this without using a form submit - I just want it to send the variable via ajax on page load. 我正在尝试不使用表单提交来执行此操作-我只希望它在页面加载时通过ajax发送变量。 Attempting to echo or print the variable $myvariable results in a blank page. 尝试回显或打印变量$ myvariable会导致空白页。 Also trying to use this variable in an API call gives me a warning that the field is blank. 另外,尝试在API调用中使用此变量也会提示我该字段为空。

I can see what you want to do but unfortunately its logic is misplaced. 我可以看到您要执行的操作,但不幸的是它的逻辑放错了位置。

PHP loads before Javascript since the server parses it before sending to your browser. PHP会在Javascript之前加载,因为服务器会先解析它,然后再将其发送到您的浏览器。 So $myvariable has no value until it receives it from the AJAX request, which doesn't come until after the page has actually loaded. 因此, $myvariable直到从AJAX请求接收到它之前都没有值,直到页面实际加载之后才出现。 Since the new version of the page isn't being re-requested, you don't see anything new appear. 由于不需要重新请求页面的新版本,因此看不到任何新内容。

You need a way to communicate the variable from the PHP file back to the browser dynamically. 您需要一种将变量从PHP文件动态传递回浏览器的方法。 This is done using JSON or something similar to send variables back to Javascript directly for parsing in the browser. 这是使用JSON或类似的方法完成的,可以将变量直接发送回Javascript以便在浏览器中进行解析。

Once you have the JSON library on your server, you'll set the dataType: json in your Javascript and in your PHP you call json_encode($responseData); 在服务器上拥有JSON库后,您将在Javascript和PHP中设置dataType: json ,然后调用json_encode($responseData); .

Oh yeah and like the others said: 哦,是的,就像其他人说的那样:

var myvariable = document.getElementByID('idforelement');

Read this to make ajax call : jQuery Ajax 阅读此文件以进行ajax调用: jQuery Ajax

And use document.getElementByID('element_id').innerHTML OR document.getElementByName(' ').innerHTML to get element's innerHTML value. 并使用document.getElementByID('element_id').innerHTMLdocument.getElementByName(' ').innerHTML document.getElementByID('element_id').innerHTML来获取元素的innerHTML值。

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

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