简体   繁体   中英

How to call a javascript function through AJAX?

i know this question is a bit silly, i am building a tool for my assignment.This tool takes the form from a website and its js files etc. My problem is that i have been told to call the javascript function by AJAX, the javascript which does the validation..

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form> 

here is the js function

function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
   alert("First name must be filled out");
  return false;
  }
}

how can i use AJAX to call the validateForm() function ??

AJAX is not used with that purpose.

If you need a javascript call to the backend server, then you make an AJAX call.

In your case you should just call your validateForm() method.

If you need an ajax to a js file in your server, you can use this with jQuery:

$.getScript( "./somefile.js" )
 .done(function( script, textStatus ) {
   console.log( textStatus );
 })
 .fail(function( jqxhr, settings, exception ) {
  // some code if it fails
});

And always consult the documentation: http://api.jquery.com/jquery.getscript/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM