简体   繁体   English

Javascript变量通过Ajax传递给PHP

[英]Javascript Variable passing to PHP with Ajax

I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP. 我最近刚开始使用Ajax,但是遇到一些我觉得非常简单的事情:在PHP中存储JS变量。

Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work? 假设我要存储一个邮政编码(使用Javascript分配),然后通过AJAX将其传递给PHP变量:为什么这样不起作用?

Keeping it simple for demonstration purposes, but this is the functionality I desire.. 出于演示目的,使其保持简单,但这是我想要的功能。

zipCode.js: zipCode.js:

$(document).ready(function() {

var zip = '123456';
    $.ajax({
    url: 'zip.php',
    data: {zip_code:zip},
    type: 'POST'
    });
});

zip.php: zip.php:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>

</head>
<body>
<?php

echo $_POST['zip_code'];

?>

</body>
</html>

An error: "Notice: Undefined index: zip_code" is all that is returned. 返回的全部为错误:“ Notice:Undefined index:zip_code”。 Shouldn't "123456" be echo'd out? 不应回显“ 123456”吗?

You are supposed to put this: 您应该这样:

<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>

on a separate page, that is not an HTML page. 在单独的页面(不是HTML页面)上。 AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. AJAX只是发送到该页面,因此您可以使用它并将其回显,在此之前进行数据库查询,或者您拥有什么。 Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code . success ,在这种情况下,如果使用data作为参数,您将看到echo的结果作为传递给success方法的参数, zip_code的结果将保存在data.zip_code Also, set your dataType:'JSON' in $.ajax({/*here*/}) . 另外,在$.ajax({/*here*/})设置您的dataType:'JSON'

Here: 这里:

var zip = '123456';
$.ajax({
  url: 'zip.php',
  data: {zip_code:zip},
  type: 'POST',
  dataType: 'JSON',
  success: function(data){
    // in here is where you do stuff to your page
    console.log(data.zip_code);
  }
});

When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing. 当您加载页面时,正在对zip.php的服务器进行调用,但是该请求绝不会链接到您当前正在查看的页面。

If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd 如果您查看对ajax请求的响应-您将看到页面的副本,其中包含正确的邮政编码回显

The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option. 然后,实际答案取决于您到底要做什么(以及代码的简化版本),以便为您提供最佳选择。

The current setup you have doesn't make sense in practice 您当前的设置在实践中没有意义

That is not how AJAX works. 那不是AJAX的工作方式。 Thake a look at the example below. 看下面的例子。 It will make an AJAX post to handle_zip.php and alert the results ( Received ZIP code 123456 ) 它将在AJAX发布到handle_zip.php并警告结果( 收到的邮政编码123456

start_page.html: start_page.html:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
    This is just a static page.
</body>
</html>

zipcode.js: zipcode.js:

$(document).ready(function() {
    var zip = '123456';
        $.ajax({
        url: 'handle_post.php',
        data: {zip_code:zip},
        type: 'POST',
        success: handleData
        });
    });
}

function handleData(data) {
    alert(data);
}

handle_post.php: handle_post.php:

<?php
die ('Received ZIP code ' . $_POST['zip_code']);

As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. 正如其他人提到的那样,听起来您希望这两位代码可以同时运行。 The reality is that: 现实情况是:

  • zip.php will be parsed on the server (and resulting in the error) zip.php将在服务器上解析(并导致错误)
  • Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed) 然后,服务器将HTML提供给浏览器(由于解析PHP时不存在$ _POST,因此正文为空白)
  • browser will see the javascript .ready() and run that code 浏览器将看到javascript .ready()并运行该代码
  • server will handle the POST request to zip.php, and generate the HTML you're expecting. 服务器将处理对zip.php的POST请求,并生成您期望的HTML。 It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. 它会在AJAX响应中返回,但是由于您不处理响应,因此在当前会话中什么也没有显示。 (you can see the POST response using any of the common web developer tools) (您可以使用任何常用的Web开发人员工具查看POST响应)

Remember, PHP runs on the server, then any javascript runs on the client. 记住,PHP在服务器上运行,然后所有javascript在客户端上运行。 You're also missing the step of handling the response from the request you made in your javascript. 您还缺少处理您在javascript中提出的请求的响应的步骤。

try this to give you better idea of what's happening. 尝试此操作可让您更好地了解正在发生的事情。

$.ajax({
  url: 'zip.php',
  data: {zip_code:zip},
  type: 'POST'
});.done(function(data ) {
  console.log(data)
});

In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. 在您的代码中,服务器首先创建了页面,因此尚未运行javascript,因此由于$ _POST ['zip_code']不存在而创建了错误。 Then it sends this page to your browser and you can see that. 然后它将页面发送到您的浏览器,您可以看到它。 At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console. 此时,当您的浏览器执行javascript时,它将再次发送请求,现在带有POST数据,服务器应该返回请求的响应,您应该可以在控制台中看到它。

You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like 您可以制作这2个单独的页面,一个用于查看页面,另一个用于处理ajax请求,或者如果您想在同一页面中对您的应用程序进行处理,则需要if语句来消除该错误,就像是

if(isset($_POST['zip_code'])){ 
    echo $_POST['zip_code];
}

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

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