ajax没有通过javascript向php发送数据

时间:2017-05-18 06:53:50

标签: javascript php ajax

JS

function myFunction() {
    var query = '?';
    var str = $("form").serialize();
    var x = $("#results").text(query += str);
    return x;
}
$("input[type='sel'], input[type='text']").on("click", myFunction);
$("select").on("change", myFunction);

//window.alert(myFunction());


var jsonString = JSON.stringify(myFunction);
$.ajax({
    type: 'POST',
    url: 'insert_value.php',
    data: {
        data: jsonString
    },
    cache: false,

    success: function () {
        alert("OK");
    }
});

insert_value.php

<?php
$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }


$src1= $_POST['data'];
$array = explode(",", $src1);

print_r($array);


  ?>

这里我编写了用于生成查询字符串的java脚本,我将该数组传递给ajax,将该数组发送到php并打印值

这里只有查询字符串生成但不使用ajax

将其发送到php

1 个答案:

答案 0 :(得分:2)

像这样更改myFunction 变量声明错误 。所以我的函数没有返回序列化数据

 function myFunction() {
     var query = '?';
     var str = $("form").serialize();
     $("#results").text(query += str);
     var x = $("#results").text();
     return x;
 }

并且

更改

var jsonString = JSON.stringify(myFunction)

 var jsonString = JSON.stringify(myFunction());

工作示例

&#13;
&#13;
var obj = {
name:$('#name').val(),
age:$('#age').val(),
one:$('#one').val(),
two:$('#two').val(),
three:$('#three').val(),
}
console.log(JSON.stringify(obj))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input value="hi" id="name" name="one">
  <input value="hi"  id="age" name="one">
  <input value="hi"  id="one" name="one">
  <input value="hi" id="two" name="one">
  <input value="hi"  id="three" name="one">

</form>
<p id="results"></p>
&#13;
&#13;
&#13;