【问题标题】:send a post oneway with jquery.post使用 jquery.post 单向发送帖子
【发布时间】:2012-07-10 03:17:52
【问题描述】:

我有一个变量,我们将调用 test_string,我也分配了字符串“hello”。

var test_string = "hello";

我希望它以单向方式发布到 php 页面 我试过了:

$.post('php_page.php', test_string);

在我使用的 php_page.php 上:

$new_var = $_POST['test_string'];
echo $new_var;

并没有得到任何结果。我在 $.post() 中遗漏了什么?

【问题讨论】:

  • 您希望它在哪里回显?该请求是在“幕后”完成的,因此除非您对返回数据进行处理(查看 jQuery ajax 文档)或使用 Chrome 的开发人员工具之类的工具,否则您将看不到任何内容。此外,$.post 在您的情况下不应将简单字符串作为数据,变量名称不会随请求一起发送。
  • 您的帖子语法错误。请参阅文档中的正确语法。

标签: php javascript jquery post


【解决方案1】:

试试这个 ---

$.post('php_page.php', {test_string:test_string});

告诉我

编辑我的工作代码 ---

test.php


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function handle(){
var test_string = "hello";
$.post('myphp.php', {'test_string':test_string},
function (result){
$("span").html(result);
});
}
</script>

</head>

<body>

<input type="button" onclick="handle();" value="Click" />
<span></span>

</body>
</html>

myphp.php

<?php
$new_var = $_POST['test_string'];
echo $new_var;

【讨论】:

  • 呃。不确定它会起作用。这里哪一部分会处理php返回的数据?
【解决方案2】:

正如 swapnesh 所暗示的,你错过了 $.post 期望一个对象作为第二个参数:

$.post('php_page.php', { objkey : objval });

然后在 PHP 中你用这个来检索它:

$val = $_POST['objkey'];

【讨论】:

    【解决方案3】:

    在 http 请求中,post 和 get 都以名称/值对的形式发送值。在您的代码中,您缺少两件事。第一件事是您尝试仅发送数据而不将其分配给名称/值对。第二件事是您还没有编写捕获服务器响应的函数。

    请尝试如下。

    $.post('php_page.php', test_string: "hello", function(response) {
     alert(response);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-16
      • 2021-10-15
      • 2013-03-16
      • 1970-01-01
      • 2011-09-06
      • 2011-06-23
      • 1970-01-01
      相关资源
      最近更新 更多