【问题标题】:jquery cannot post with ajax phpjquery 无法使用 ajax php 发布
【发布时间】:2015-08-24 19:40:34
【问题描述】:

我有一个简单的脚本,我想在其中使用 AJAX 将数据发布到服务器,然后将其吐出(回显),但它不起作用...

这是我的输出:

Your viewport width is 1338x684

Ajax wasn't initialized!

并且在这种情况下,宽度和高度仅在 PHP 脚本没有获取任何数据时设置为 880px * 495px。

testajax.php的网页头:

<head>
<script type='text/javascript' src='js/jquery-1.7.2.min.js'></script>       <!-- Main Java library script-->
<!-- The following 3 scripts are utilized by the Accordion Menu in the aside side bar -->
<script type='text/javascript' src='js/jquery.cookie.js'></script>          <!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.hoverIntent.minified.js'></script><!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.dcjqaccordion.2.7.min.js'></script> <!-- Acco. Menu script-->
<!--The following 2 scripts are utilized by the Pan and Zoom Slide Show -->
<script type="text/javascript" src="js/jquery.carouFredSel-6.2.1.js"></script>
<script type="text/javascript" src="js/panzoomslideshow.js"></script>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Testing Ajax</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/normalize.min.css">        <!-- used to normalize-->
        <link rel="stylesheet" href="css/main.css">                 <!-- Main CSS styling-->

<script type="text/javascript">
document.write('<p>Your viewport width is '+ window.innerWidth+'x'+window.innerHeight+'</p>');

$(document).ready(function() {
    $.ajax({
            url: "ajaxresponse.php",
            type: "POST",
            dataType: "json",   
            data: {
                width        : window.innerWidth,
                height       : window.innerHeight
            },    
            success: function( data, textStatus, jQxhr ){
                $("#response pre").html( JSON.stringify( data ) );
            },
            error: function( jqXhr, textStatus, errorThrown ){
            console.log( errorThrown );
            }
        });
});
</script>


<!-- ********** panzooom.php prints the java script to make a pan and zoom transition slide show, depending on the width and heigth of the viewport *********** -->

             <!--[if lt IE 9]>
                <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
                <script>window.html5 || document.write('<script src="js/vendor/html5shiv.js"><\/script>')</script>
            <!--<![endif]--> 
    <?php include 'ajaxresponse.php';?>                 
</head>

这里是 ajaxresponse.php 文件:

<?php  
if (is_ajax()) {
    if (isset($_POST["data"]) && !empty($_POST["data"])) { //Checks if data value exists
        $data = $_POST["data"];
        echo "Ajax was initialized :)<br>";
        echo '<p>var_dump($_POST):<br>'; 
        var_dump( $_POST );    
    }else{
        "Ajax was initialized, but the value isn't set or it's empty (same same)!<br>";
    }
}else{
echo "Ajax wasn't initialized!<br>";    
}


//Function to check if the request is an AJAX request
function is_ajax() {
    echo "\$_SERVER['HTTP_X_REQUESTED_WITH']  ->   " . $_SERVER['HTTP_X_REQUESTED_WITH'] . "<br>";
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?> 

【问题讨论】:

  • 您是否查看过浏览器的开发者工具(-> 网络资源)并实际看到 AJAX 请求已关闭?还有I want to post data using AJAX to the server and then spit it out (echo), but it won't work... 到底是什么意思?我的意思是it won't work 不是错误描述。就好像患者会去看医生并说I'm hurt
  • 问题是,你为什么要关闭处理并将contentType设置为JSON,然后你试图将数据作为$_POST['width']获取,就好像它是www-encoded一样't, 现在是 JSON 了?
  • 虽然可能不会导致问题,但您应该将 PHP 的输出从 &lt;head&gt; 元素移动到 &lt;body&gt; 元素中。
  • 获得了所有三个 cmets,并将尝试移动代码并研究如何将其从 JSON 更改为简单的字符串文本。在开发人员工具下,我得到了控制台和网络,我也会尝试为您提供这些信息。
  • adeneo - 我在我的 Comodo 浏览器(基本上是 Chrome)中截取了网络部分的屏幕截图,在 XHR 下有一个各种文件的列表,主要是带有状态、类型、启动器、大小和时间的 .js,连同时间线。在这个列表中,我找到了 testajax.php,它的大小是 7.0KB,时间是 1.65 秒,这难道不是表明某些东西被触发了吗?

标签: php jquery ajax post


【解决方案1】:

问题 1

在这里你告诉 jQuery,当它发出请求时:

  • 应该说是发送JSON
  • 不应将您传递的数据转换为其他格式
contentType: 'application/json',            
processData: false,

这里你不要传递 JSON

data: {
    width        : window.innerWidth,
    height       : window.innerHeight
},

在 PHP 中:

您尝试从 $_POST 读取,如果请求格式为 JSON,则不会初始化。

isset($_POST["data"]

从您的 JavaScript 中删除 contentType 和 processData 配置。让 jQuery 默认使用表单编码对数据进行编码。


问题 2

您正在尝试读取一条名为 data 的数据:

$data = $_POST["data"];

但您发送的唯一数据片段称为widthheight

data: {
    width        : window.innerWidth,
    height       : window.innerHeight
},

您需要测试您实际发送的数据。

问题 3

您说 (dataType: 'json',) 您希望响应中包含 JSON,但 testajax.php 返回一个 HTML 文档。

【讨论】:

  • 嗨昆汀 - 你说得很有道理。我删除了 contentTypeprocessData,同时保持 dataTypejson 我正在测试是否有数据,在我尝试转储内容之前。计划是达到这一点,然后开始弄清楚如何使用它。我仍然得到输出 Ajax 没有初始化! - 所以拼图中还缺少其他东西(以及)......
  • $_SERVER['HTTP_X_REQUESTED_WITH'] 的值是多少? (当您使用 Ajax 请求 URL 时,而不是直接将其加载到浏览器中时)。
  • 嗨 Quentin - 在我使用 Ajax 请求 URL 时,我不完全确定如何检查 $_SERVER['HTTP_X_REQUESTED_WITH'] 的值。由于我只需要几个数字或字符串(宽度和高度),我宁愿远离 JSON,但我没有任何运气将 dataType 设置为 文本 要么 - 检查is_ajax() 时我不断得到一个错误我对JQuery BTW 很陌生...
  • 只需echo 它(并查看开发人员工具的“网络”选项卡以查看响应的样子……假设您已经在做,否则您看不到它输出的内容响应您的 Ajax 请求)
  • 看起来testajax.php既是浏览器直接请求时加载HTML文档的脚本,也是Ajax请求时加载某些特定数据的脚本。虽然将这两个东西放在同一个 URL 上通常有很好的理由,但如果你将它们分成两个单独的文件并独立测试它们,你会更容易调试它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2021-08-23
  • 2018-12-02
相关资源
最近更新 更多