使用ajax和php,ajax的返回结果为什么一直是php代码?

html代码:

 <html>
    <head>
        <script src="jquery-1.3.2.js"></script>
        <script>
            $(function(){
                $("#helloBtn").click(function(){
                    $.ajax({
                        url: "test.php",
                        type: "POST",
                        success: function(res){
                                    alert(res);
                                },
                        error: function(msg){
                                    alert('error');
                                }
                    });                 
                });
            });
        </script>
    </head>

    <body>
        <button id="helloBtn">hello</button>
    </body>
</html>

php代码:

 <?php
    echo 'hello';
?>

结果:
图片说明

我用的是apache服务器。

5个回答

服务器上安装php了么?
这里有个php的安装教程:http://www.cnblogs.com/timmmmit/archive/2017/10/22/7709483.html

如果你嫌麻烦,也可以找一键安装包。比如xampp安装。

新建一个index.php
编写

<?php
    echo phpinfo();
?>

如果通过浏览器访问输出了php的版本信息,那么说明php是安装正确了的。

把你要选择的数据类型写到ajax里面,dataType:json

请确保在服务器上已经安装php和相应模块

你把 url: "test.php", 这个换成具体的function 名,然后在方法里面写就好,出现这个原因是你什么都没有传给,回调函数!

可以试试在ajax参数里加个datatype:"text",然后php里不用echo,使用return

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
通过AJAX的PHP POST请求返回源代码

<div class="post-text" itemprop="text"> <p>I am trying to send POST and retrieve data from that POST. Instead I get the source code of my AJAX script (<code>ajax.php</code>).</p> <pre><code>&lt;?php $params = array('action' =&gt; 'LOL'); $query = http_build_query($params); $contextData = array( 'method' =&gt; 'POST', 'content' =&gt; $query ); $context = stream_context_create(array('http' =&gt; $contextData)); $result = file_get_contents( 'ajax.php', false, $context ); var_dump($result); ?&gt; </code></pre> <p>What gives?</p> </div>

利用ajax调用php查询数据库为什么返回data值为php整个文件的字符串

想利用ajax验证用户名在数据库中有无重复,但是ajax调用php后返回data为整个php文件的字符串。 求解 ajax部分: ``` $("#username").blur(function () { // 取用户名 var u = $("#username").val();//取输入的用户名 alert(u); //调ajax $.ajax({ url: "checkName.php", data: {u: u},//第二个u只是变量,可以随意写,checkName.php里面的u是第一个。 type: "POST", dataType: "TEXT", success: function (data) { if (data.trim() == "OK")//要加上去空格,防止内容里面有空格引起错误。 { alert("该用户存在"); //window.location.href = "main.php";//js跳转页面,要记住。 } else if(data.trim() == "NO") { alert("该用户不存在"); //echo("用户名不存在,重新输入用户名或者注册"); } else alert("数据库调用错误"+data); } }); }); }); ``` php部分: ``` <?php $uid = $_POST["u"]; $con = mysql_connect("localhost","root","123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mywebbase", $con); $result = mysql_query("SELECT * FROM web"); if (mysql_field_len($result) > 0) { // 输出数据 echo "OK" } else { echo "NO"; } mysql_close($con); ?> ```

原生js实现ajax请求为什么responseText返回的是PHP代码

``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="result"></div> <div> <form action=""> 用户名:<input type="text" id="username" value="admin"> 密码:<input type="password" id="password" value="123456"> <input type="button" value="登录" id="btn"> </form> </div> </body> </html> <script> window.onload = function(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; var btn = document.getElementById("btn"); btn.onclick = function(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else { xhr = new ActiveXObject("Mcrosoft XMLHTTP"); } url = "./request.php?username="+username+"&password="+password; xhr.open("get",url,true); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var data = xhr.responseText;//xhr.responseText获取到了被请求的PHP代码,为什么? // alert(data); // if(text == 1){ // document.getElementById("result").innerHTML = "login success"; // } // if(text == 2){ // document.getElementById("result").innerHTML = "login faild"; // } } } } } } </script> ``` ``` <?php $username = $_GET['username']; $password = $_GET['password']; if($username == 'admin' && $password == '123456'){ echo 1; }else{ echo 2; } ?> ```

php后台怎么返回数据到ajax啊,ajax怎么接收呢

表单提价后做出的提示我想用弹框的形式显示出来,PHP后台怎么返回这个值到ajax呢,我这样写的报错,![图片说明](https://img-ask.csdn.net/upload/201609/28/1475054107_490566.png)![图片说明](https://img-ask.csdn.net/upload/201609/28/1475054119_174380.png)![图片说明](https://img-ask.csdn.net/upload/201609/28/1475054127_505861.png)

如何使用AJAX调用PHP函数,并获取返回值?

<div class="post-text" itemprop="text"> <p>I want to call a specific function from my <code>database.php</code> file, and get the returned value. Here I am trying to do this:</p> <p>js:</p> <pre><code>function submit_verification_code(){ $.ajax({ url: "database.php", type: "post", data: ({ 'code': code_entered, }), dataType:"text", context: this, success : function(response) { console.log('RESPONSE: ' + response); //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_RESPONSE(response); }, error: function(jqXHR,textStatus,errorThrown){ //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_ERROR(jqXHR); console.log(errorThrown); } }); } </code></pre> <p>database.php</p> <pre><code> if(isset($_POST['code'])){ does_code_match($_POST['code']); } function does_code_match($code){ connect(); die('test'); $sql = 'select * from emailstobeverified where email='; $sql .= "'" . $_SESSION['email'] . "'"; $sql .= ' and verification_code='; $sql .= $code; $sql .= ';'; $count = query($sql)-&gt;num_rows; die(strval($count)); disconnect(); echo strval($count); exit; //Once you've outputted, make sure nothing else happens } </code></pre> <p><code>does_code_match</code> function executes, and the console log prints <code>&lt;br /&gt;</code> when <code>console.log("RESPONSE" + response)</code> is called. But I want it to print the value of <code>$count</code></p> <p>EDIT:</p> <p>There is a problem with <code>connect()</code> function. If I call <code>die('test')</code> just before calling <code>connect()</code>, it returns a response! It says "hello world" in the console. If I call it directly AFTER calling <code>connect()</code>, it prints this:</p> <pre><code>&lt;b&gt;Warning&lt;/b&gt;: Use of undefined constant conn - assumed 'conn' (this will throw an Error in a future version of PHP) in &lt;b&gt;C:\xampp2\htdocs\database.php&lt;/b&gt; on line &lt;b&gt;72&lt;/b&gt;&lt;br /&gt; &lt;br /&gt; &lt;b&gt;Warning&lt;/b&gt;: Use of undefined constant dbhost - assumed 'dbhost' (this will throw an Error in a future version of PHP) in &lt;b&gt;C:\xampp2\htdocs\database.php&lt;/b&gt; on line &lt;b&gt;72&lt;/b&gt;&lt;br /&gt; &lt;br /&gt; &lt;b&gt;Warning&lt;/b&gt;: Use of undefined constant dbuser - assumed 'dbuser' (this will throw an Error in a future version of PHP) in &lt;b&gt;C:\xampp2\htdocs\database.php&lt;/b&gt; on line &lt;b&gt;72&lt;/b&gt;&lt;br /&gt; &lt;br /&gt; &lt;b&gt;Warning&lt;/b&gt;: Use of undefined constant dbpass - assumed 'dbpass' (this will throw an Error in a future version of PHP) in &lt;b&gt;C:\xampp2\htdocs\database.php&lt;/b&gt; on line &lt;b&gt;72&lt;/b&gt;&lt;br /&gt; &lt;br /&gt; &lt;b&gt;Warning&lt;/b&gt;: Use of undefined constant db - assumed 'db' (this will throw an Error in a future version of PHP) in &lt;b&gt;C:\xampp2\htdocs\database.php&lt;/b&gt; on line &lt;b&gt;72&lt;/b&gt;&lt;br /&gt; test </code></pre> <p>and the response is <code>&lt;br /&gt;</code></p> <p>Connect function:</p> <pre><code> $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $db = "example"; $conn; function connect(){ $GLOBALS[conn] = new mysqli($GLOBALS[dbhost], $GLOBALS[dbuser], $GLOBALS[dbpass],$GLOBALS[db]) or die("Connect failed: %s ". $GLOBALS[conn] -&gt; error); } </code></pre> </div>

如何使用ajax返回并处理php文件返回的数组?

<div class="post-text" itemprop="text"> <p>I've a php file which processes a query and returns an array.</p> <p>How do i get these and array and parse them and display them using ajax.</p> <p>I call the file using ajax. Its used to display the matching products while typing a text box with the price...</p> <p>responseText doesn't return anything...</p> </div>

使用jQuery AJAX函数调用返回PDF的php文件

<div class="post-text" itemprop="text"> <p>My php file: example_061.php create PDF return and everything works fine.</p> <p>Now I want to call that file with jQuery AJAX to get this at my screen and I try:</p> <pre><code>$("#proba").click(function() { //in here we can do the ajax after validating the field isn't empty. $.ajax({ url: "tcpdf/examples/example_061.php", type: "POST", async: true, data: { ime: $("#ime").val(), pozicija: $("#pozicija").val(), jmbg: $("#jmbg").val() }, //your form data to post goes here as a json object dataType: "html", success: function(response) { window.open('example_061.pdf'); }, }); }); </code></pre> <p>Everything is fine so success function work an I get alert message but I don't get PDF file as download or at screen. How I can do that?</p> </div>

Ajax当执行成功响应结果无法返回?

一下是我手写的ajax调用代码,onreadystatechange 调用的方法未执行 返回结果我用firefox 可以检测到响应已经成功,并且有内容返回,可是 [code="javascript"]alert(xmlhttp.responseText); document.getElementById("ajaxtest").innerHTML=xmlhttp.responseText;[/code] 就是未执行 不知道为什么? [code="javascript"]var xmlhttp; function ajaxtest() { xmlhttp=GetXmlHttpObject(); xmlhttp.onreadysatechange=function() { if(xmlhttp.readysate==4 || xmlhttp.status==200) { alert(xmlhttp.responseText); document.getElementById("ajaxtest").innerHTML=xmlhttp.responseText; } } xmlhttp.open("Get","test.php?msg=i am OK!",true); xmlhttp.send(); } function GetXmlHttpObject() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; }[/code]

如何使用AJAX调用PHP函数?

<div class="post-text" itemprop="text"> <p>I'm running my server on <code>localhost</code> using XAMPP, and I want to call a Javascript function which sends some data from the browser to a php script</p> <p>The JS function is called when the a button on my html page is pressed:</p> <pre><code>function send_verification_code(){ var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhttp.open('GET','database.php?email='+email_address) xhttp.send() } </code></pre> <p>So I want to add, to the <code>$_GET</code> array, a key-value pair of <code>email=&gt;email_address</code>, where <code>email_address</code> is a string, in the function above. </p> <p>Immediately after the function above executes, I want to call another function, a PHP function which adds that data to a SQL database on my server by calling <code>add_email_to_be_verified</code> (the function belongs to the php script im sending the data to):</p> <p>database.php:</p> <pre><code>&lt;?php $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $db = "example"; $conn; function add_email_to_be_verified(){ connect(); $sql = 'insert into emailstobeverified values('; $sql .= $_GET['email']; $sql .= ','; $sql .= generate_verification_code(); $sql .= ','; $sql .= date("Y-m-d H:i:s"); $sql .= ');'; query($sql); disconnect(); } function generate_verification_code(){ //generates a random 6-digit verification code $code = mt_rand(0,999999); $padded_code = sprintf('%06d', $code); return $padded_code; } function connect(){ $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s ". $conn -&gt; error); } function query(sql){ $conn-&gt;query($sql); } function disconnect(){ $conn -&gt; close(); } ?&gt; </code></pre> <p>How can I call the php function using AJAX?</p> </div>

如何使用AJAX将PHP响应返回到HTML页面

<div class="post-text" itemprop="text"> <p>I am trying to learn web applications, here I have my client side using HTML and server is PHP based. I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX. So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error". </p> <p>So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.</p> <p>I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.</p> <p>Here is the code </p> <p><strong>PHP:</strong> </p> <pre><code>&lt;?php include ( "./inc/connect.inc.php" ); header("Content-type: application/javascript"); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, GET"); session_start(); if (isset($_SESSION['user_login'])) { $user = $_SESSION["user_login"]; } else { $user = ""; } ?&gt; &lt;?php $registration = @$_POST['signup-submit']; $fname = @$_POST['fname']; $lname = @$_POST['lname']; $uname = @$_POST['uname']; $email = @$_POST['email']; $email_repeat = @$_POST['email_repeat']; $password = @$_POST['password']; $ucheck_array = array('Username Takne'); $echeck_array = array('Email already used'); $siginup_sucess_array = array('Sucess'); //Sign-Up form validation if ($registration) { $usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' "); $usernamecount = mysql_num_rows($usernamecheck); $emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' "); $emailcount = mysql_num_rows($emailcheck); if ($usernamecount == 0 &amp;&amp; $emailcount == 0) { $squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" ); echo json_encode($siginup_sucess_array); } else { if ($usernamecount == 1) { echo json_encode($ucheck_array); } else if ($emailcount == 1) { echo json_encode($echeck_array); } } } </code></pre> <p><strong>HTML Form:</strong></p> <pre><code>&lt;form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;"&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="dob" id="dob" placeholder="D-O-B" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="email" name="email" id="email" placeholder="Email" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value=""&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value=""&gt; &lt;/div&gt; &lt;div class="form-group dob"&gt; &lt;input type="text" name="date" id="date" placeholder="Date" value=""&gt; &lt;/div&gt; &lt;p class="index_p"&gt;By creating the account you accept all the &lt;span style="color: #4CAF50; font-weight: bold; text-decoration: underline;"&gt;Terms &amp; Conditions.&lt;/span&gt;&lt;/p&gt; &lt;div class="form-group"&gt; &lt;div class="row"&gt; &lt;div id="btn_signin" class="col-sm-6 col-sm-offset-3"&gt; &lt;input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;div id="signup-test"&gt;&lt;/div&gt; //PHP response to be displayed here </code></pre> <p><strong>JS:</strong></p> <pre><code>$("#signup-submit").click( function() { $.post( $("#register-form").attr("action"), $("#register-form :input").serializeArray(), function(signup_data){ $("#signup-test").html(signup_data); }); clearInput(); }); $("#register-form").submit( function() { return false; }); function clearInput() { $("#register-form :input").each( function() { $(this).val(''); }); } </code></pre> <p>To be clear I tried <code>e.preventDefault</code>, <code>return false</code> and many other scripts, and my PHP and HTML are not in the same folder or directory. Thanks. </p> </div>

使用AJAX根据下拉框返回查询结果

<div class="post-text" itemprop="text"> <p>I know that this is a popular question and I have looked at many examples trying to get my head around <code>AJAX</code> and <code>jQuery</code>.</p> <p>I have a simple situation with one drop down box when changed sends an <code>AJAX</code> request for the results of an <code>SQL</code> query based on the drop down box selection. </p> <p>The page loads correctly and the function is being called when a department is being chosen from the drop down box (the alert tells me that) but I am not getting any return data. In trying to identify the problem how can I tell whether the getTeachers.php file is actually running?</p> <p><strong>Web page</strong> Script for calling getTeacher.php on the server</p> <pre><code>&lt;script src="http://localhost/jquery/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; function checkTeacherList(str) { var xmlhttp; if (str=="") { document.getElementById("txtTeacher").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { document.getElementById("txtTeacher").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getTeachers.php?q="+str,true); xmlhttp.send(); alert(str); //To test it is getting this far, which it does } &lt;/script&gt; </code></pre> <p>Drop down box and txtTeacher ID for return data from server</p> <pre><code>&lt;select name="department_list" id="department_list" onchange="checkTeacherList(this.value);" &gt; &lt;?php $options[0] = 'All'; $intloop = 1; while($row = mysql_fetch_array($department_result)) { $options[$intloop] = $row['departmentName']; $intloop = $intloop + 1; } foreach($options as $value =&gt; $caption) { echo "&lt;option value=\"$caption\"&gt;$caption&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;div id="txtTeachers"&gt;Teacher names&lt;/div&gt; </code></pre> <p><strong>Server side PHP - getTeachers.php</strong></p> <pre><code>&lt;?php $q=$_GET["q"]; $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error($con)); } $db_selected = mysql_select_db("iobserve"); $sql="SELECT * FROM departments WHERE departmentName = '".$q."';"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { echo $row['teacherName']; } mysql_close($con); ?&gt; </code></pre> </div>

php+ajax返回结果问题,急急急,求帮忙!

php+ajax代码在本地测试很正常,但是放到服务器上就出现了错误,错误提示(Uncaught SyntaxError: Unexpected token  in JSON at position 0)本地测试的时候不存在这个问题。 本地PHP版本5.6,服务器上的PHP版本5.3. 把返回的json数据在线验证的时候出现一下情况 ![图片说明](https://img-ask.csdn.net/upload/201710/19/1508390240_604652.png) 琢磨了几天都找不到问题所在,请各位大侠帮忙!!

为什么这个AJAX调用正确的php脚本没有返回任何东西?

<div class="post-text" itemprop="text"> <p>I posted a similar question earlier, just I did not realize that the code I put had an obvious bug in it (not supplying the data) which I new existed. Now I am redoing it with that because I am still having the problem.</p> <p>I have this AJAX:</p> <pre><code>function sendMail(){ $.ajax({ type: "POST", url: "../prestige-auto/php/sendMail.php", data: {"message" : $('#contactMessage').html(), "email" : $('#contactEmail').val(), "name" : $('#contactName').val()}, success: function(result){ if (result == 'success') { alert(result); } else { alert(result); } } }); }; $('#submitContact').click(function(){ sendMail(); }) </code></pre> <p>and this PHP:</p> <pre><code>&lt;?php $trimmed = array_map('trim', $_POST); $message = $trimmed['message']; $email = $trimmed['email']; $name = $trimmed['name']; if (empty($message)) { $message = FALSE; } if (empty($email)) { $message = FALSE; } if (empty($name)) { $message = FALSE; } if ($message &amp;&amp; $email &amp;&amp; $name){ $body = "From: $name. $message"; mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email"); echo ('success'); } echo($message.' '.$email.' '.$name); ?&gt; </code></pre> <p>All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?</p> </div>

Ajax发布到PHP返回空数组

<div class="post-text" itemprop="text"> <p>I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.</p> <p>Ajax request in 'adopt.php':</p> <pre><code>var info = JSON.stringify(filteredArray); $.ajax({ type: 'POST', url: 'ajax.php', data: {'info': info}, success: function(data){ console.log(data); } }); </code></pre> <p>ajax.php code:</p> <pre><code>if(isset($_POST['info'])){ $_SESSION['array'] = $_POST['info']; } </code></pre> <p>back in adopt.php, later:</p> <pre><code>if(isset($_SESSION['array'])){ $arr = $_SESSION['array']; echo "console.log('information: ' + $arr);"; } </code></pre> <p>in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)</p> </div>

ajax返回值一直是null???

``` <script> $(function(){ $(".getMore").click(function(){ var cid = $(this).attr("cid"); // var doPost = "GetSunLists"; $.ajax({ type:"post", url:"http://localhost/kq/index.php/Home/Curl/curlEdit", data:{"cid":cid}, async: false, dataType:"json", success:function(data){ alert(data); } }); }); }) </script> ```

Ajax传值和PHP接收,请大神帮忙看下

![这是Ajax代码](https://img-ask.csdn.net/upload/201507/30/1438231424_379684.png) ![这是chrome显示](https://img-ask.csdn.net/upload/201507/30/1438231522_677996.png) ![这是PHP代码](https://img-ask.csdn.net/upload/201507/30/1438231602_790590.png) 问题是:php代码里面什么都不写Ajax传值成功,PHP代码里面写个echo都失败。PHP框架是CodeIgniter 。

我可以使用PHP从JQuery AJAX请求返回输出状态吗?

<div class="post-text" itemprop="text"> <p>I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:</p> <pre><code>$.ajax({ url: "script.php", data: { value: value }, type: 'post', success: function(output){ alert(output); } }); </code></pre> <p>However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.</p> <p>I tried the error option:</p> <pre><code>... success: function(output){ alert(output); }, error: function(output){ // do something } </code></pre> <p>but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.</p> <p>In pseudo-code, I'm looking for something like this:</p> <pre><code>$.ajax({ url: "script.php", data: { value: value }, type: 'post', success: function(output){ if(output.status == 0){ alert(output); }else{ // do something else } } }); </code></pre> <p>Is anything of the sort possible? Thanks for any and all help!</p> </div>

用ajax调用php并返回多个变量?

<div class="post-text" itemprop="text"> <p>I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.</p> <p>This is my JS.</p> <pre><code> $.ajax({ url: 'test.php', data: { id : lastFileId }, success: function(output) { alert(output); } }); </code></pre> <p>my PHP</p> <pre><code>&lt;?php $fileId = ($_GET['id']); $num1 = 1; $num2 = 2; ?&gt; </code></pre> <p>From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?</p> <p>also this is a very basic idea of what I have planned to do if I can achieve this.</p> </div>

admin-ajax.php返回0

<div class="post-text" itemprop="text"> <p>I'm currently working on a WordPress contact form, which is created as a plugin. I need the form after submit to send an email without reloading the page. When it reloads everything is ok. The problem is when submit button is pressed and e.preventDefault() is active the browser shows me <strong>500 (Internal Server Error)</strong> with <strong>admin-ajax.php = 0</strong></p> <p>P.S The post is edited</p> <pre><code> &lt;?php add_action( 'admin_footer', 'html_form_code' ); // Write our JS below here // function html_form_code() { ?&gt; &lt;form action="&lt;?php esc_url( $_SERVER['REQUEST_URI'] )?&gt;" method="post" class="contact-form" id="contact-form" &gt; &lt;div class=header-contact&gt; &lt;p&gt;&lt;h2&gt;Contact Form&lt;/h2&gt;&lt;/p&gt; &lt;hr&gt; &lt;/div&gt; &lt;div class=input-containers&gt; &lt;input type="text" id="name" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="" size="40" placeholder="Име и фамилия"/&gt; &lt;/div&gt; &lt;div class=input-containers&gt; &lt;input type="email" id="email" name="cf-email" value="" size="40" placeholder="Поща"/&gt; &lt;/div&gt; &lt;div class=input-containers&gt; &lt;input type="text" id="subject" name="cf-subject" pattern="[a-zA-Z ]+" value="" size="40" placeholder="Относно"/&gt; &lt;/div&gt; &lt;div class=input-containers&gt; &lt;textarea rows="10" id="message" cols="35" name="cf-message" placeholder="Текст"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class=input-containers&gt; &lt;input type="submit" name="cf-submitted" value="Send" id="submitForm"&gt; &lt;/div&gt; &lt;p id="verify" style="display:none;"&gt;Your message has been sent.&lt;br /&gt;&lt;br /&gt;&lt;/p&gt; &lt;/form&gt; &lt;script&gt; jQuery('#contact-form').submit(function(e){ e.preventDefault(); var name = jQuery('#name').val(); var email = jQuery('#email').val(); var subject = jQuery('#subject').val(); var message = jQuery('#message').val(); jQuery.ajax({ url: '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;', type: "POST", data:{ action: 'send_email', name: name, email: email, subject: subject, message: message, }, success:function(res){ alert("Email Sent."); } }); }); &lt;/script&gt; &lt;?php } add_action( 'wp_ajax_send_email', 'deliver_mail' ); add_action( 'wp_ajax_nopriv_send_email', 'deliver_mail' ); function deliver_mail() { require_once "wp-includes/class-phpmailer.php"; if (isset($_POST["cf-submitted"])) { // sanitize form values $name = sanitize_text_field( $_POST["cf-name"] ); $email = sanitize_email( $_POST["cf-email"] ); $subject = sanitize_text_field( $_POST["cf-subject"] ); $message = esc_textarea( $_POST["cf-message"] ); // get the blog administrator's email address //$to = "email@gmx.com"; $headers = "From: $name &lt;$email&gt;" . " "; // Localhost $mail = new PHPMailer(true); $mail-&gt;IsSMTP(); // telling the class to use SMTP $mail-&gt;CharSet = 'UTF-8'; $mail-&gt;SMTPDebug = 0; // enables SMTP debug information (for testing) $mail-&gt;SMTPAuth = true; // enable SMTP authentication $mail-&gt;SMTPSecure = "ssl"; // sets the prefix to the servier $mail-&gt;Host = "mail.gmx.com"; // sets GMX as the SMTP server for example: mail.gmx.com $mail-&gt;Port = 465; // set the SMTP port for the GMX server $mail-&gt;Username = $email; $mail-&gt;Password = 'pass'; $mail-&gt;SetFrom($email, $name); $mail-&gt;AddAddress($email); $mail-&gt;Subject = $subject; $mail-&gt;MsgHTML($message); $headers .= "Content-Type: text/html; charset=utf-8"; $headers .= "Content-Transfer-Encoding: 8bit"; try { $mail-&gt;send(); $msg = "An email has been sent for verfication."; $msgType = "success"; wp_safe_redirect( home_url(), 302 ); exit(); } catch (Exception $ex) { $msg = $ex-&gt;getMessage(); $msgType = "warning"; wp_safe_redirect( home_url(), 302 ); exit(); } add_action( 'init', function() { if ( ! empty( $_POST['form_submitted'] ) ) { deliver_mail(); } }); function cf_shortcode() { ob_start(); //deliver_mail(); html_form_code(); //ob_end_flush(); return ob_get_clean(); } add_shortcode( 'contact_form_second', 'cf_shortcode' ); </code></pre> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

ArrayList源码分析(入门篇)

ArrayList源码分析 前言: 写这篇博客的主要原因是,在我上一次参加千牵科技Java实习生面试时,有被面试官问到ArrayList为什么查找的速度较快,插入和删除的速度较慢?当时我回答得不好,很大的一部分原因是因为我没有阅读过ArrayList源码,虽然最后收到Offer了,但我拒绝了,打算寒假学得再深入些再广泛些,下学期开学后再去投递其他更好的公司。为了更加深入理解ArrayList,也为

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

玩转springboot启动banner定义所得

最近接手了一个springboot项目,不是不熟悉这个框架,启动时打印的信息吸引了我。 这不是我熟悉的常用springboot的打印信息啊,我打开自己的项目: 还真是的,不用默认的感觉也挺高大上的。一时兴起,就去研究了一下源代码,还正是有些收获,稍后我会总结一下。正常情况下做为一个老程序员,是不会对这种小儿科感兴趣的,不就是一个控制台打印嘛。哈哈! 于是出于最初的好奇,研究了项目的源代码。看到

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

立即提问
相关内容推荐