如何在jquery中拆分ajax的Response html


How to split the Response html of ajax in jquery

代码运行正常。但我不能溢出html的响应使用ajax jquery。我需要把它分割为#div1和#div2。请使用"|"分割响应。请用完整的代码解释。因为我对jquery了解不多。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var Names = $('#Names').val();//alert(Names);
        var ArrNames = Names.split(",");
        var Name1 = ArrNames[0];//alert(Name1);
        var Name2 = ArrNames[1];//alert(Name2);
        $("#div1").load('result.php', {
            "FirstName": Name1,
            "SecondName": Name2
        });
        return (false);
    });
});
</script>
</head>
<body>
<div style="float:left;"><b>Response Data1:</b></div><div id="div1" style="float:left;"></div><br><br><br>
<div style="clear:both;">
<div style="float:left;"><b>Response Data2:</b></div><div id="div2" style="float:left;"></div><br><br><br>
<div style="clear:both;">
<form>
<input id="Names" type="text" value="name1,name2">
<button>Event</button>
</form>
</body>
</html>

this is result.php

<?php
       $name1 = $_REQUEST['FirstName'];
       $name2 = $_REQUEST['SecondName'];
// i need to split by | this symbol;
    ?> 
<input type="text" value="This is 1st response <?php echo $name1;?>"> | This is 2nd Response <?php echo $name2;?>

嘿,再一次:D这里是ajax文档http://api.jquery.com/jquery.ajax/和一些代码。

<form id="form">
  <input id="Names" type="text" value="name1,name2">
  <input type="submit">
</form>

// I would use $("#form").submit(function() {}) instead of $.click()
$("#form").submit(function(){
    var Names = $('#Names').val();//alert(ArrNames);
    var ArrNames = Names.split(",");
    var Name1 = ArrNames[0];//alert(Name1);
    var Name2 = ArrNames[1];//alert(Name2);
    $.ajax({
      url: "result.php",
      method: "POST",
      data: {"FirstName": Name1, "SecondName": Name2}
    }).done(function(response) {
      var splitted = response.split("|"); // RESULT
      $("#div1").html(splitted[0]); // The first name
      $("#div2").html(splitted[1]); // The secondname
    });
});
// Also change your php to this, so it is compatible
<?php
  $name1 = $_POST['FirstName'];
  $name2 = $_POST['SecondName'];
  ...
编辑:


您可以使用split()函数示例拆分响应(如上所述)

"name 1 | name 2".split("|") -> ["name 1 ", " name 2"]